Spring security remember me - spring

As per this link, I'm trying to implement the Persistent Token Approach for the "remember me" functionality. The tokens are stored in my database (postgres). I have the datasource set up properly, however, when I try doing:
<remember-me data-source-ref="dataSource" />
My database does not get populated with the token data automatically. Otherwise, the "remember me" functionality works well (only the database doesn't get populated automatically). Any ideas why?
Table ddl:
create table users(
uid serial primary key,
username varchar(255) not null,
password varchar(255) not null,
firstname varchar(255) not null,
lastname varchar(255) not null,
enabled boolean not null,
constraint cs_username_unq unique(username),
constraint cs_uid_username_unq unique(uid, username)
);
create table authorities (
username varchar(255) not null,
authority varchar(255) not null,
constraint fk_authorities_users foreign key(username) references users(username)
);
create unique index ix_auth_username on authorities (username,authority);
create table persistent_logins (
username varchar(255) not null,
series varchar(255) primary key,
token varchar(255) not null,
last_used timestamp not null
);

Related

How to make a relation field that shows a list of users with additionnal fields

The plugin I've created has two tables with these structures :
CREATE TABLE notifications (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
`sent_at` DATETIME NULL DEFAULT NULL,
`title` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`message` TEXT NOT NULL COLLATE 'utf8mb4_unicode_ci',
`photo` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`icon` VARCHAR(191) NOT NULL COLLATE 'utf8mb4_unicode_ci'
)
CREATE TABLE notification_recipients(
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
`notification_id` INT(11) NOT NULL,
`user_id` INT(11) NOT NULL,
`seen` TINYINT(1) NOT NULL,
`archived` TINYINT(1) NOT NULL
)
I can't figure out how to create a relation to show a backend select field where I can select users to get the notification, what should be done in the model.
I will later process the form in the controller in order to create the notification_recipients line to every user selected.
After reading and watching the tutorial about relations, I've come to understand I might need a pivot table.
But I need the notification_recipients table in order to process the notification later to show custom queries in frontend (seen and archived fields will determine the visibility in frontend).
How can I do that ? I don't understand the relationship I'm trying to build, shouw I have a third table ?
Thank you, best regards.
Update (solution found) :
I added a Checkbox List named "users".
According to the docs of OctoberCMS, you can add options from the model to a Radio field, and Checkbox Lists work the same way.
For now, I got it working by doing this in the Model used for the form:
use RainLab\User\Models\User;
...
public function getUsersOptions($value, $formData)
{
$users = User::all();
$mapped = $users->mapWithKeys(function ($item) {
return [$item['id'] => $item['name']];
});
return $mapped;
}
It worked great and I'm getting all users with their ids.

Spring Boot with Vaadin - using foreign keys

I am new to Spring Boot and Vaadin. I followed a tutorial to create CRUD pages for a phone book application however I am having trouble using foreign keys. I have a Contact table which has phone type (i.e. cell or home) as a foreign key - i.e. it is referenced to my PhoneType table. I am stuck on how to populate the phone type from a drop down of values populated in my PhoneType table. Right now I am I have the following member variable in my Contact class
#ManyToOne
#JoinColumn(name="type")
private PhoneType phoneType;
And in my PhoneType class I have
#Column(name = "type")
private String phoneType;
However I am getting an error that says "Error executing DDL via JDBC Statement".
The rest of the application works well with the CRUD pages.
Firstly in mySQL implementations you can't store actual objects unless you use 8.0+ JSON data type. SQL has no idea what a PhoneType is because it's an object and not a valid data type. https://www.w3schools.com/sql/sql_datatypes.asp
If you want to store actual objects you need to find a noSQL implementation that you like.
So your "Customer" class doesn't map to a table properly. You would need to make instance variables such as
String hasCellPhone, hasHomePhone; //etc for the options in your dropdown menu
instead of trying to put a phonetype object.
I asked almost the exact same question, I suggest you read this entire thread.
https://stackoverflow.com/a/50879597/5468597
create table item (
barcode bigint not null auto_increment primary key,
name varchar(20) not null,
type varchar(20) not null,
is_available boolean not null,
is_late boolean null,
notes varchar(255) null,
check_out_date datetime null,
due_date datetime null
#create index idx_barcode (barcode));
create table patron (
trinity_id bigint not null primary key,
name varchar(30) not null,
email varchar(20) not null,
owes_fines boolean not null,
fines_owed int null
#create index idx_trinity_id (trinity_id));
create table checked_out_items (
ref_id bigint primary key auto_increment not null,
patron_id bigint not null,
item_id bigint not null,
item_available boolean not null,
item_check_out_date datetime null,
item_due_date datetime null);
alter table checked_out_items
add constraint fk_patron_id
foreign key (patron_id) references patron(trinity_id),
add constraint fk_item_id
foreign key (item_id) references item(barcode)
#add constraint fk_item_available
#add constraint fk_check_out_date
#add constraint fk_due_date
#foreign key (item_available references item(is_available)
#foreign key (item_check_out_date) references item(check_out_date)
#foreign key (item_due_date) references item(due_date)
on update cascade
on delete cascade;
insert into patron values(0000000,'Test Erino','test#erino.edu',0,null);
insert into item values(1,'Chromebook','Laptop',0,null,null,null,null);
insert into checked_out_items(patron_id,item_id,item_available,item_check_out_date,item_due_date)
select patron.trinity_id,item.barcode,item.is_available,item.check_out_date,item.due_date
from patron
inner join item;
and lastly:
select * from item;
select * from patron;
select * from checked_out_items;
I won't post the java logic here. That's for you to read in the other thread.
I solved my question.
#ManyToOne (cascade = {CascadeType.ALL})
#JoinColumn(name="phoneType_typeId")
private PhoneType phoneType;
And
#Id
#GeneratedValue
#Column(name = "typeId")
private Long id;

Role based dashboard in spring security

CREATE TABLE `role_details` (
`role_id` int(11) NOT NULL AUTO_INCREMENT,
`role_name` varchar(45) DEFAULT NULL,
`role_desc` varchar(100) DEFAULT NULL,
`rights` varchar(300) DEFAULT NULL,
PRIMARY KEY (`role_id`)
)
CREATE TABLE `user_details` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`display_name` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
`emp_id` int(11) DEFAULT NULL,
`role` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`mobile` varchar(45) DEFAULT NULL,
`creation_time` datetime DEFAULT CURRENT_TIMESTAMP,
`status` varchar(45) DEFAULT NULL,
PRIMARY KEY (`user_id`)
)
This is my database schema. I am using spring security.
But I am confused...what I need to write in spring-security.xml ?
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query=
"SELECT * FROM hmis_db.user_details where display_name=? and status='active'"
authorities-by-username-query=
"**QUESTION** " />
</authentication-provider>
</authentication-manager>
Actually, I want to create Role based dashboard. and 'rights' in role_details table that specifies the access menu list..and according it it will generate role based dashboard.
Actually I can't see the relationship between your UserDetails table and the RoleDetails one, maybe I'm losing something.
When I have made such a kind of entities schemas, I allways made a 1-to-n relations between Users and roles, so one user can have one role or more.
But assumming you are conguring a 1-1 relation from user to role, and assuming the ROLE_xxx you are looking for is on the role field in UserDetails table, your authorities-by-username-query must be more or less like this:
"select display_name as username, role as authority from user_details where display_name =? "
If the field role in user_details is the foreign key which must match the field role_name in role_details, and rigths are actually the authorities which are referenced in access elements of security_intercept urls, it should be this way:
"select u.display_name as username, r.rights as authority
from user_details as u INNER JOIN role_details as r ON u.role = r.role_name
where u.display_name =? "
But here you might have a trouble if rights are a comma separated list of authorities. authorities-by-username-query expects to receive a list of rows with an authority in each of this rows. If this is what you were seeking, you should consider changing the schema or making even a view of the tables which returns a right per row result
EDIT: I should do this way:
This is the creation script:
CREATE TABLE IF NOT EXISTS `role_details` (
`role_id` INT(11) NOT NULL AUTO_INCREMENT,
`role_name` VARCHAR(45) NULL DEFAULT NULL,
`role_desc` VARCHAR(100) NULL DEFAULT NULL,
`role_authority` VARCHAR(300) NOT NULL,
PRIMARY KEY (`role_id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `user_details` (
`user_id` INT(11) NOT NULL AUTO_INCREMENT,
`display_name` VARCHAR(45) NULL DEFAULT NULL,
`password` VARCHAR(45) NULL DEFAULT NULL,
`emp_id` INT(11) NULL DEFAULT NULL,
`email` VARCHAR(45) NULL DEFAULT NULL,
`mobile` VARCHAR(45) NULL DEFAULT NULL,
`creation_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
`status` TINYINT(1) NULL DEFAULT 0,
PRIMARY KEY (`user_id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `user_role_details` (
`user_details_user_id` INT(11) NOT NULL,
`role_details_role_id` INT(11) NOT NULL,
PRIMARY KEY (`user_details_user_id`, `role_details_role_id`),
INDEX `fk_user_details_has_role_details_role_details1_idx` (`role_details_role_id` ASC),
INDEX `fk_user_details_has_role_details_user_details_idx` (`user_details_user_id` ASC),
CONSTRAINT `fk_user_details_has_role_details_user_details`
FOREIGN KEY (`user_details_user_id`)
REFERENCES `user_details` (`user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_user_details_has_role_details_role_details1`
FOREIGN KEY (`role_details_role_id`)
REFERENCES `role_details` (`role_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
Note I deleted column 'role' in user_details, renamed 'rights' to 'role_authority' in role_details and changed 'status' from varchar to tinyint(1) to use it as boolean.
Then, the user details sqls:
users-by-username-query=
"SELECT display_name as username, password, status as enabled
FROM user_details as u WHERE u.display_name = ? and status = 1;"
authorities-by-username-query=
"Select u.display_name as username, r.role_authority as authority
FROM
user_details as u
INNER JOIN user_role_details as urd ON u.user_id = urd.user_details_user_id
INNER JOIN role_details as r ON urd.role_details_role_id = r.role_id
WHERE u.display_name = ?"
This way you can have multiple roles binded to each user
Refer to following link that covers basics and example http://en.tekstenuitleg.net/blog/spring-security-with-roles-and-rights
Once you familiarize yourself with basics, please look deeper into Spring Security documentation https://docs.spring.io/spring-security/site/docs/3.0.x/reference/ns-config.html before you implement that code for production.
If you are using Spring Security 4, you may prefer annotations based configurations like
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("userpwd").roles("USER");
auth.inMemoryAuthentication().withUser("admin").password("adminpwd").roles("ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.and().formLogin()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}

Get data from another table into form of Joomla

I am creating a component for Joomla! 2.5 and I have the following MySQL table structure.
CREATE TABLE `#__table_a` (
id INT NOT NULL AUTO_INCREMENT,
actividad VARCHAR( 255 ),
publish_up DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
publish_down DATETIME NOT NULL
);
CREATE TABLE `#__table_b` (
id INT NOT NULL AUTO_INCREMENT,
table_a_id INT NOT NULL, /*foreign key to table '#__table_a' field 'id'*/
hora TIME NOT NULL,
created DATETIME NOT NULL,
publish_up DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
publish_down DATETIME NOT NULL
);
What I want is that, in the form where I managed data from "# __table_a", I need to be able to manage data that is listed in the table "#__table_b".
How do I do it?,
Ie where do I do the "query" for such data and to display them in the form?, in the "table_a" model or controller?

FULL TEXT SEARCH in cakephp ? any example

I am using ordinary search functionality in my business controller . but
now need to implement FULL TEXT SEARCH with paginate can any one give idea or sample ?
I am using MySQL with MyISAM tabes
and this my table structure, fields marked bold are need to use in
search
CREATE TABLE IF NOT EXISTS businesses (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
created date NOT NULL,
modified datetime NOT NULL,
user_id bigint(20) NOT NULL,
slug varchar(255) NOT NULL,
**`name` varchar(255) NOT NULL,**
**street_name varchar(255) DEFAULT NULL,**
**shopping_center varchar(255) DEFAULT NULL,**
state_id int(10) NOT NULL,
suburb_id int(10) NOT NULL,
zip_code varchar(12) DEFAULT NULL,
website varchar(250) DEFAULT NULL,
email varchar(255) DEFAULT NULL,
phone_no varchar(255) NOT NULL,
mobile_no varchar(255) DEFAULT NULL,
fax varchar(255) DEFAULT NULL,
is_active tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
After you have created your FULLTEXT indices it's not different at all from normal paginate conditions, you just need to construct your SQL a little more manually and most importantly escape the user input manually.
$query = 'foobar'; // the user input to search for
$escapedQuery = $this->Business->getDataSource()->value($query);
$this->paginate['conditions'] = array("MATCH (Business.name) AGAINST ($escapedQuery)");
$businesses = $this->paginate();

Resources