WS10
This commit is contained in:
@@ -1,15 +1,33 @@
|
||||
package dev.service;
|
||||
|
||||
import dev.dao.UserDao;
|
||||
import dev.model.User;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
public class AuthService {
|
||||
|
||||
private final UserDao userDao = new UserDao();
|
||||
|
||||
public boolean register(String username, String password, String email) {
|
||||
|
||||
// TODO:
|
||||
// Validate and register user
|
||||
|
||||
return false;
|
||||
if (username == null || username.isBlank() || password == null || password.isBlank()) {
|
||||
System.out.println("Username and password are required.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (userDao.findByUsername(username) != null) {
|
||||
System.out.println("Username already exists.");
|
||||
return false;
|
||||
}
|
||||
|
||||
User user = new User(0, username, hashPassword(password), email);
|
||||
|
||||
return userDao.save(user);
|
||||
}
|
||||
|
||||
public User login(String username, String password) {
|
||||
@@ -17,7 +35,44 @@ public class AuthService {
|
||||
// TODO:
|
||||
// Authenticate user
|
||||
|
||||
return null;
|
||||
User user = userDao.findByUsername(username);
|
||||
|
||||
if (user == null) {
|
||||
System.out.println("Invalid username or password.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!user.getPassword().equals(hashPassword(password))) {
|
||||
System.out.println("Invalid username or password.");
|
||||
return null;
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
private String hashPassword(String password) {
|
||||
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hashedBytes = digest.digest(password.getBytes());
|
||||
|
||||
StringBuilder hexString = new StringBuilder();
|
||||
|
||||
for (byte b : hashedBytes) {
|
||||
String hex = Integer.toHexString(0xff & b);
|
||||
|
||||
if (hex.length() == 1) {
|
||||
hexString.append('0');
|
||||
}
|
||||
|
||||
hexString.append(hex);
|
||||
}
|
||||
|
||||
return hexString.toString();
|
||||
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user