|
|
|
|
@ -0,0 +1,46 @@
|
|
|
|
|
package com.mathgenerator.auth;
|
|
|
|
|
|
|
|
|
|
import com.mathgenerator.model.Level;
|
|
|
|
|
import java.util.Map;
|
|
|
|
|
import java.util.Optional;
|
|
|
|
|
import java.util.stream.Stream;
|
|
|
|
|
import java.util.stream.Collectors;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 负责用户身份验证。
|
|
|
|
|
*/
|
|
|
|
|
public class Authenticator {
|
|
|
|
|
|
|
|
|
|
private static final Map<String, User> USER_DATABASE = initializeUsers();
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 初始化预设的用户数据。
|
|
|
|
|
*/
|
|
|
|
|
private static Map<String, User> initializeUsers() {
|
|
|
|
|
return Stream.of(
|
|
|
|
|
new User("张三1", "123", Level.PRIMARY),
|
|
|
|
|
new User("张三2", "123", Level.PRIMARY),
|
|
|
|
|
new User("张三3", "123", Level.PRIMARY),
|
|
|
|
|
new User("李四1", "123", Level.JUNIOR_HIGH),
|
|
|
|
|
new User("李四2", "123", Level.JUNIOR_HIGH),
|
|
|
|
|
new User("李四3", "123", Level.JUNIOR_HIGH),
|
|
|
|
|
new User("王五1", "123", Level.SENIOR_HIGH),
|
|
|
|
|
new User("王五2", "123", Level.SENIOR_HIGH),
|
|
|
|
|
new User("王五3", "123", Level.SENIOR_HIGH)
|
|
|
|
|
).collect(Collectors.toMap(User::username, user -> user));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 验证用户登录凭据。
|
|
|
|
|
* @param username 用户名
|
|
|
|
|
* @param password 密码
|
|
|
|
|
* @return 如果验证成功,返回包含User的Optional;否则返回空的Optional。
|
|
|
|
|
*/
|
|
|
|
|
public Optional<User> login(String username, String password) {
|
|
|
|
|
User user = USER_DATABASE.get(username);
|
|
|
|
|
if (user != null && user.password().equals(password)) {
|
|
|
|
|
return Optional.of(user);
|
|
|
|
|
}
|
|
|
|
|
return Optional.empty();
|
|
|
|
|
}
|
|
|
|
|
}
|