User service added login and returning token

This commit is contained in:
Filip Izydorczyk
2020-09-14 12:39:25 +02:00
parent 8c16b2f3d1
commit 11f3625684
7 changed files with 151 additions and 3 deletions

View File

@ -1,5 +1,7 @@
package com.plannaplan.entities;
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@ -14,11 +16,35 @@ public class User {
private Long id;
private String name;
private String surname;
private String email;
private UserRoles role;
private String token;
private Date tokenCreatedDate;
public User() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getTokenCreatedDate() {
return tokenCreatedDate;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.tokenCreatedDate = new Date(System.currentTimeMillis());
this.token = token;
}
public String getName() {
return name;
}

View File

@ -0,0 +1,13 @@
package com.plannaplan.exceptions;
public class UserNotFoundException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public UserNotFoundException(String message) {
super(message);
}
}

View File

@ -3,9 +3,12 @@ package com.plannaplan.repositories;
import com.plannaplan.entities.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("FROM User WHERE email = ?1")
User getByAuthority(@Param("authority") String authority);
}

View File

@ -1,6 +1,10 @@
package com.plannaplan.services;
import java.util.UUID;
import com.plannaplan.abstracts.EventWatcher;
import com.plannaplan.entities.User;
import com.plannaplan.exceptions.UserNotFoundException;
import com.plannaplan.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
@ -15,4 +19,22 @@ public class UserService extends EventWatcher {
super();
}
public String login(String authority) throws UserNotFoundException {
User user = this.repo.getByAuthority(authority);
if (user == null) {
throw new UserNotFoundException("Can not find user with given authority");
}
String token = UUID.randomUUID().toString();
user.setToken(token);
return token;
}
public void save(User user) {
this.repo.save(user);
}
public User getUserByEmail(String email) {
return this.repo.getByAuthority(email);
}
}

View File

@ -1,5 +1,5 @@
package com.plannaplan.types;
public enum UserRoles {
STUDENT, DEANERY, ADMIN
STUDENT, DEANERY, ADMIN, TEST_USER
}