I am building web application where i am building the first stage with user registration and login.
I am thinking of
class User
{
private userid;
private firstname
.........
//getters and setters
}
class UserService {
public boolean authenticate(username, password) {}
public addUser()
public saveuser()
public ConfirmEmail()
public resetPassword()
......
}
I have few questions
Is my approach correct?
Also i have diff function in front end and for backend admin user, so should i put all in one class or, i have to make diff for front end and backend?
As this is the most common thing which every organisation requires, so is it possible to find it from internet so that i can see how enterprise people approach this?
First thing, I'd look at whether you can use another authentication system like Google or Facebook, or Open ID (StackOverflow uses these and more).
Secondly, I'd look into using a security framework like Spring Security.
Finally, if you want/need to do it on your own from scratch, here are some pointers
Always store passwords using a 1-way hashing mechanism e.g. SHA
Use salt when hashing your password - you should have a random salt value per password (see this SO question for it's length)
You can also have a constant application-wide salt value that is not stored next to the password
Give the users roles. This will solve your front end/back end users problem
I'm assuming you're using a database. Here's an example schema (MySQL)
CREATE TABLE users (
id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT
mail VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
enc_password VARCHARCHAR(64) NOT NULL,
salt CHAR(8) NOT NULL,
is_mail_authenticated TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
UNIQUE KEY (mail)
) ENGINE = InnoDB;
CREATE TABLE roles (
id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT
name VARCHAR(32) NOT NULL,
UNIQUE KEY (name)
) ENGINE = InnoDB;
CREATE TABLE users_roles (
user_id NTEGER UNSIGNED NOT NULL,
role_id NTEGER UNSIGNED NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (roel_id) REFERENCES roles (id),
) ENGINE = InnoDB;
That'll do it for a very basic user model. You'll need a tool to generate your salt. I'd use randomAlphanumeric from Apache commons lang.
You may want to add some stuff to lock user accounts after too many failed login attempts. And you may want to track the IP with which they've logged in from. This is left as an exercise to the reader :)
I added the is_mail_authenticated field to track whether the user had authenticated their mail. This is usually accomplished by clicking a link from one's email.
I think, Spring provides very good approach for creating user with role assignment and authenticating the user powerfully, and also maintaining the security or your application. No need to implement whole as our own application, you can use spring security.
http://static.springsource.org/spring-security/site/start-here.html
Either you can create users by your own do the authentication using above security plugins.
Related
I'm new to PostgreSQL and Java Swing.
In PostgreSQL company database, I have a users table and it has 4 fields: user_id, username, phone, and address.
CREATE TABLE users
(
user_id serial primary key,
username VARCHAR(40) not null,
phone VARCHAR(14) not null,
address VARCHAR(50)
);
I'm trying to load all fields from users table to JTable in Java Swing using Bound (Figure 1).
Then I bind the elements from the table (Figure 2).
As you can see in Figure 2, it shows only 3 fields except user_id. I need to load this user_id field as well because I need to perform CRUD data.
How can I achieve that?
I finally got the solution.
When I import the data from the database to the form, the Model (for example; Users.java) file is generated.
The problem was I firstly generated that file and later I added the user_id column to the database, so guess what, the Model file is somehow not updated and so the user_id is not there.
Therefore, I had manually added getter and setter for the user_id field, and now ok.
I'm building an app that allows each user to select whether they want to register as a player, and optionally as an admin. They can register as both a player AND an admin, but can only have ONE current role -> i.e. can only log in as either player/admin at the given time.
I'm using a Player-Role pattern in which Player and Admin class extend the abstract UserRole class.
What table structure should I create to support this in a way that:
I can store a list of the roles the user has registered for
I can store and retrieve on demand the CURRENT User Role for User
For example, I would like to have the following code be supported by database to get the current Role of user in Player.getRole() and one similar one for Admin.getRole():
User userWithID = User.getUser(userWithID);
UserRole playerRole = null;
List<UserRole> userRoles = userWithID.getRoles();
for(UserRole role : userRoles){
if(role instanceof Player){
playerRole = role;
break;
}
}
if(playerRole == null) throw new IllegalAccessError("Player with ID does not exist");
else{
return (Player) playerRole;
}
The problem arises that i need two kinds of information from user roles. 1- the roles registered for, and 2- the current role. And UserRole is abstract.
NB: Before you mark this as duplicate:
All the other questions on StackOverflow don't have answers that indicate how to get the current user role for a user, or don't have implementations specified under this domain model.
Since you tagged database-design, I'll show a possible table design for that:
CREATE TABLE users (
user_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
...
);
CREATE TABLE roles (
role_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
...
);
CREATE TABLE user_has_role (
user_id bigint REFERENCES users NOT NULL,
role_id bigint REFERENCES roles NOT NULL,
PRIMARY KEY (user_id, role_id)
);
CREATE TABLE current_role (
user_id bigint PRIMARY KEY REFERENCES users,
role_id NOT NULL,
FOREIGN KEY (user_id, role_id) REFERENCES user_has_role
);
The first three tables contain the static information and the fourth us updated whenever the user logs in.
My Spring Boot web app uses form authentication with spring-boot-security.
I have two tables:
User
CREATE TABLE user
(
id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password CHAR(60) NOT NULL,
//...
);
Role
CREATE TABLE role
(
id INT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
r_name VARCHAR(45) NOT NULL
);
CREATE UNIQUE INDEX sys_role_r_name_uindex ON sys_role (r_name);
Join table
CREATE TABLE ref_user_role
(
user_id INT(11) NOT NULL,
role_id INT(11) NOT NULL,
// ...
);
In order to add more users with other roles/priviledges, one has to be of role ROLE_ROOT in sys_role table. This root user has to exist before the add-more-users action, logically.
What I have tried is that
I ran a sql script containing the root-user-insertion statement before I deployed the app. Obviously, I had to also manually generate an encrypted password for this root user.
I grammatically run an sql script to insert the root credentials. My concern is that it might not be safe to include my ROOT user credentials in the data.sql file. If I put encrypted version of the password, I have to encrypt it beforehand.
Another way I can think of is that I can create a root-creation-page ONLY the first time the app starts. I will need a secret code(only the I and the app knows) in addition to the username and password so that no other random people can create the root account.
Are these the common ways to do this?
If not, what are some of the good ways?
If you're using Spring Boot, all you have to do is to place schema.sql and data.sql scripts within resources classpath.
The schema.sql will be in charge of creating your tables and associations between them, and the data.sql will be in charge of initializing your tables with data, so you can put there your insert into tables statements.
when you upload the service these scripts will be executed automatically by Spring Boot each upload.
for further reading take a look at:
http://docs.spring.io/spring-boot/docs/1.4.2.RELEASE/reference/htmlsingle/#howto-database-initialization
I am new in java and I am trying to do a simple project to get familiar with that.
So, I am working on a dynamic web application which I use tomcat as server and MySQL with hibernate provider.
I want to be able to write persian or arabic alphabets in my tables. but unfortunately I cannot.
I have written this query for my database tables:
DROP DATABASE IF EXISTS myDb;
CREATE DATABASE myDb CHARSET = utf8 COLLATE = utf8_general_ci;
USE myDb;
drop table if exists user;
drop table if exists resume;
create table resume(
resumeId INTEGER NOT NULL AUTO_INCREMENT,
resumeDescription NVARCHAR(255),
PRIMARY KEY (resumeId)
) charset = utf8;
create table user(
userId INTEGER NOT NULL AUTO_INCREMENT,
username NVARCHAR(40) NOT NULL,
password varchar(20) NOT NULL,
email varchar(50) NOT NULL,
resumeId INTEGER UNIQUE,
PRIMARY KEY (userId),
FOREIGN KEY (resumeId) REFERENCES resume(resumeId)
) charset = utf8;
I have tried to insert persian alphabets. I have created a form and made a servlet for that to handle the request. I've got parameters from the request and tested them. At that moment they were ok and they were shown properly. but when I insert them in database I face with this:
(the question marks are persian alphabets)
I dont know what to do and what is the problem.
I have searched for this problem on the internet and tested different ways but none of them worked in my case.
Can anyone please help me to write persian alphabets properly in mySql database?
by the way my connection url is this:
jdbc:mysql://localhost:3306/myDb?zeroDateTimeBehavior=convertToNull
Try using the following connection url:
jdbc:mysql://localhost:3306/myDb?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8
This will force the driver to use UTF-8.
I have a Spring new web application(Java), and after having the user login (using username and password), I want to make the user able to add a new user, till then all is good. Each user have a primary Key iduser which autoincrimented (AI), and a foreign key idprofile. The table Profile contain informations about the user, and it's idprofile is the primary key (which have to be the same as the ipdrofile in User table).
As you may know, MySQL don't let you make more than one AI per table (MySQL 5 workbench as platform), and when my code add's an user, it has to add a profile in the same time, but with three fields that are unknown, which are iduser, idprofile (user table) and idprofile (profile table). As the ipdrofile can't be an AI, how can I manage to put the right key on it when saving the User and Profile (Adding) ?
You insert the profile first, returning the new profile id, then you insert the user, using the returned profile id, optionally returning the new user id if you need it.
You'll need to use these two methods to get the auto-generated key returned:
Connection.prepareStatement(String, String[])
Statement.getGeneratedKeys()