feat: add model groups, verified registration and CNY credit grants

This commit is contained in:
wlx committed 2026-09-18 17:27:58 +08:00
1 parent f5ba6cb255
commit 7a18db2123
40 files changed
+1980 -263

No files matched your search

@@ -26,26 +26,44 @@ import org.springframework.web.bind.annotation.RestController;
public class AuthController {
private static final String SESSION_COOKIE = "moyi_session";
private final AuthService authService;
private final VerificationService verification;
private final int sessionTtlHours;
private final boolean secureCookie;
public AuthController(
AuthService authService,
VerificationService verification,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours,
@Value("${moyi.auth.secure-cookie}") boolean secureCookie
) {
this.authService = authService;
this.verification = verification;
this.sessionTtlHours = sessionTtlHours;
this.secureCookie = secureCookie;
}
public record LoginRequest(String account, String password) {}
public record RegisterRequest(String invitationCode, String account, String password, String displayName) {}
public record RegisterRequest(String invitationCode, String account, String password, String displayName, String verificationCode) {}
public record CodeRequest(String account, String invitationCode) {}
@GetMapping("/auth/verification")
public Map<String,Boolean> verificationStatus() { return verification.capabilities(); }
@PostMapping("/auth/verification")
public Map<String,Object> sendCode(@RequestBody CodeRequest input,HttpServletRequest request) {
return verification.send(input.account(),input.invitationCode(),request.getRemoteAddr());
}
public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {}
public record RoleRequest(String role) {}
public record CreateUserRequest(String account, String password, String displayName) {}
@PostMapping("/admin/users")
public ResponseEntity<Map<String,Object>> createUser(@RequestBody CreateUserRequest input, HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("user",authService.createUser(sessionToken(request),input.account(),input.password(),input.displayName(),meta(request))));
}
@PostMapping("/auth/login")
public Map<String, Object> login(
@@ -64,6 +82,7 @@ public class AuthController {
HttpServletRequest request,
HttpServletResponse response
) {
verification.consume(input.account(),input.verificationCode());
AuthService.AuthResult result = authService.register(
input.invitationCode(), input.account(), input.password(), input.displayName(), meta(request)
);
@@ -234,6 +234,25 @@ public class AuthService {
return jdbc.query("SELECT * FROM users ORDER BY created_at DESC", this::mapUser).stream().map(user -> toView(user, null)).toList();
}
@Transactional
public UserView createUser(String token, String accountInput, String password, String displayName, RequestMeta meta) {
UserView actor=requireAdmin(token);
String account=normalizeAccount(accountInput);
if(account.isBlank() || account.length()>254 || (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches() && !account.matches("[a-z0-9_]{3,64}"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱、手机号或 3 至 64 位字母数字下划线用户名");
if(password==null || password.length()<8 || password.length()>256) throw new ApiException("WEAK_PASSWORD","普通用户密码长度为 8 至 256 位");
if(findUserByAccount(account)!=null) throw new ApiException("ACCOUNT_EXISTS","账号已存在",409);
String name=displayName==null || displayName.isBlank()?defaultDisplayName(account):displayName.trim();
if(name.length()>80) throw new ApiException("INVALID_NAME","显示名称最多 80 字符");
UUID id=UUID.randomUUID();
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name,role,status) VALUES (?,?,?,?,?,'user','active')",id,account,accountKind(account),passwordHasher.hash(password),name);
authCreatedAudit(actor.id(),id,meta);
return toView(findUserById(id),null);
}
private void authCreatedAudit(UUID actor, UUID user, RequestMeta meta) {
audit("user.admin_created",actor,meta,Map.of("targetUserId",user));
}
@Transactional
public Map<String, Object> createInvitation(
String token,
@@ -0,0 +1,63 @@
package com.moyi.controlplane.auth;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.moyi.controlplane.common.ApiException;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
@Component
public class CloudVerificationSender implements VerificationSender {
private final Environment env;
public CloudVerificationSender(Environment env) { this.env=env; }
private String value(String key) { return env.getProperty(key,"").trim(); }
@Override
public boolean available(String channel) {
if("email".equals(channel)) return !value("MOYI_SMTP_HOST").isEmpty() && !value("MOYI_SMTP_FROM").isEmpty();
return !value("MOYI_SMS_ACCESS_KEY_ID").isEmpty() && !value("MOYI_SMS_ACCESS_KEY_SECRET").isEmpty() && !value("MOYI_SMS_SIGN_NAME").isEmpty() && !value("MOYI_SMS_TEMPLATE_CODE").isEmpty();
}
@Override
public void send(String channel,String account,String code) {
if(!available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
try {
if("email".equals(channel)) {
JavaMailSenderImpl mail=new JavaMailSenderImpl();
mail.setHost(value("MOYI_SMTP_HOST"));
mail.setPort(env.getProperty("MOYI_SMTP_PORT",Integer.class,465));
mail.setUsername(value("MOYI_SMTP_USERNAME"));
mail.setPassword(env.getProperty("MOYI_SMTP_PASSWORD",""));
mail.setDefaultEncoding("UTF-8");
var properties=mail.getJavaMailProperties();
properties.setProperty("mail.smtp.auth",String.valueOf(!value("MOYI_SMTP_USERNAME").isEmpty()));
properties.setProperty("mail.smtp.ssl.enable",env.getProperty("MOYI_SMTP_SSL","true"));
properties.setProperty("mail.smtp.starttls.enable",env.getProperty("MOYI_SMTP_STARTTLS","false"));
properties.setProperty("mail.smtp.starttls.required",env.getProperty("MOYI_SMTP_STARTTLS","false"));
properties.setProperty("mail.smtp.ssl.checkserveridentity","true");
properties.setProperty("mail.smtp.connectiontimeout","5000");
properties.setProperty("mail.smtp.timeout","10000");
properties.setProperty("mail.smtp.writetimeout","10000");
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom(value("MOYI_SMTP_FROM"));
message.setTo(account);
message.setSubject("MOYI 注册验证码");
message.setText("您的注册验证码为:"+code+",5 分钟内有效。请勿向他人泄露。若非本人操作,请忽略此邮件。");
mail.send(message);
} else {
Config config=new Config().setAccessKeyId(value("MOYI_SMS_ACCESS_KEY_ID")).setAccessKeySecret(value("MOYI_SMS_ACCESS_KEY_SECRET")).setEndpoint("dysmsapi.aliyuncs.com").setProtocol("https");
var client=new com.aliyun.dysmsapi20170525.Client(config);
var request=new SendSmsRequest().setPhoneNumbers(account.startsWith("+86")?account.substring(3):account)
.setSignName(value("MOYI_SMS_SIGN_NAME")).setTemplateCode(value("MOYI_SMS_TEMPLATE_CODE")).setTemplateParam("{\"code\":\""+code+"\"}");
var response=client.sendSmsWithOptions(request,new RuntimeOptions().setAutoretry(false).setConnectTimeout(5000).setReadTimeout(10000));
if(response.getBody()==null || !"OK".equals(response.getBody().getCode())) throw new IllegalStateException("SMS rejected");
}
} catch(Exception exception) {
// SDK exceptions may contain credentials or recipients. Never expose them to logs or clients.
throw new ApiException("VERIFICATION_SEND_FAILED","验证码发送失败,请稍后重试或联系管理员检查发送服务",502);
}
}
}
@@ -0,0 +1,6 @@
package com.moyi.controlplane.auth;
public interface VerificationSender {
boolean available(String channel);
void send(String channel, String account, String code);
}
@@ -0,0 +1,69 @@
package com.moyi.controlplane.auth;
import com.moyi.controlplane.common.ApiException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class VerificationService {
private final JdbcTemplate jdbc;
private final VerificationSender sender;
private final String pepper;
private final SecureRandom random=new SecureRandom();
public VerificationService(JdbcTemplate jdbc,VerificationSender sender,@Value("${moyi.auth.password-pepper}") String pepper) {
this.jdbc=jdbc; this.sender=sender; this.pepper=pepper;
}
public Map<String,Boolean> capabilities() { return Map.of("email",sender.available("email"),"phone",sender.available("phone")); }
public String normalize(String raw) {
String account=raw==null?"":raw.trim().toLowerCase(Locale.ROOT);
if(!account.contains("@")) account=account.replaceAll("[\\s-]","");
if(account.length()>254 || (!account.matches("^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$") && !account.matches("^(?:\\+86)?1[3-9][0-9]{9}$"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱或中国大陆手机号");
return account;
}
private String digest(String account,String code) { return AuthService.hashSecret(pepper+":registration:"+account+":"+code); }
@Transactional(noRollbackFor=ApiException.class)
public Map<String,Object> send(String raw,String invitation,String ip) {
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
if(!sender.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
Integer invites=jdbc.queryForObject("SELECT count(*) FROM invitation_codes WHERE code_hash=? AND disabled_at IS NULL AND used_count<max_uses AND (expires_at IS NULL OR expires_at>now())",Integer.class,AuthService.hashSecret(invitation==null?"":invitation.trim()));
if(invites==null || invites==0) throw new ApiException("INVITATION_INVALID","请先填写有效邀请码",403);
String source=ip==null?"unknown":ip;
// One global lock bounds aggregate sending and serializes account/IP limits across replicas.
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>now()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>now()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
jdbc.update("INSERT INTO registration_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,digest(account,code));
try { sender.send(channel,account,code); }
catch(ApiException exception) { jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account); throw exception; }
jdbc.update("DELETE FROM verification_send_events WHERE created_at<now()-interval '2 days'");
return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
}
@Transactional(noRollbackFor=ApiException.class)
public void consume(String raw,String code) {
String account=normalize(raw);
var rows=jdbc.queryForList("SELECT * FROM registration_codes WHERE account=? FOR UPDATE",account);
if(rows.isEmpty()) throw new ApiException("VERIFICATION_INVALID","请先获取验证码");
var row=rows.getFirst();
java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant();
if(Boolean.TRUE.equals(row.get("consumed")) || expiry.isBefore(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取");
jdbc.update("UPDATE registration_codes SET attempts=attempts+1 WHERE account=?",account);
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),digest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误");
jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account);
}
}