102 lines
7.5 KiB
Java
102 lines
7.5 KiB
Java
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.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 VerificationDispatchService dispatch;
|
|
private final String pepper;
|
|
private final SecureRandom random=new SecureRandom();
|
|
public VerificationService(JdbcTemplate jdbc,VerificationDispatchService dispatch,@Value("${moyi.auth.password-pepper}") String pepper) {
|
|
this.jdbc=jdbc; this.dispatch=dispatch; this.pepper=pepper;
|
|
}
|
|
public Map<String,Boolean> capabilities() { return Map.of("email",dispatch.available("email"),"phone",dispatch.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 purpose,String account,String code) { return AuthService.hashSecret(pepper+":"+purpose+":"+account+":"+code); }
|
|
private String registrationDigest(String account,String code) { return digest("registration",account,code); }
|
|
private String resetDigest(String account,String code) { return digest("password-reset",account,code); }
|
|
|
|
@Transactional
|
|
public Map<String,Object> send(String raw,String invitation,String ip) {
|
|
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
|
|
if(!dispatch.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);
|
|
admitSend(account,ip);
|
|
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
|
|
dispatch.enqueue(VerificationPurpose.REGISTRATION,account,code,registrationDigest(account,code));
|
|
return accepted();
|
|
}
|
|
|
|
private void admitSend(String account,String ip) {
|
|
String source=ip==null || ip.isBlank()?"unknown":ip;
|
|
// This lock covers only bounded DB work, NEVER the mail/SMS provider.
|
|
jdbc.queryForObject("SELECT set_config('lock_timeout','2s',true)",String.class);
|
|
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
|
|
jdbc.update("DELETE FROM verification_send_events WHERE id IN (SELECT id FROM verification_send_events WHERE created_at<clock_timestamp()-interval '2 days' LIMIT 500)");
|
|
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>clock_timestamp()-interval '60 seconds'",Integer.class,account);
|
|
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>clock_timestamp()-interval '24 hours'",Integer.class,account);
|
|
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>clock_timestamp()-interval '1 hour'",Integer.class,source);
|
|
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>clock_timestamp()-interval '24 hours'",Integer.class);
|
|
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
|
|
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address,created_at) VALUES (?,?,?,clock_timestamp())",UUID.randomUUID(),account,source);
|
|
}
|
|
private Map<String,Object> accepted() { 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),registrationDigest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误");
|
|
jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account);
|
|
}
|
|
|
|
@Transactional
|
|
public Map<String,Object> sendReset(String raw,String ip) {
|
|
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
|
|
if(!dispatch.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
|
|
// Exact same request-side DB/crypto path for active, unknown and disabled accounts.
|
|
// Existence is checked ONLY in the worker; no network result reaches this receipt.
|
|
admitSend(account,ip);
|
|
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
|
|
dispatch.enqueue(VerificationPurpose.PASSWORD_RESET,account,code,resetDigest(account,code));
|
|
return accepted();
|
|
}
|
|
|
|
@Transactional(noRollbackFor=ApiException.class)
|
|
public String consumeReset(String raw,String code) {
|
|
String account=normalize(raw);
|
|
var rows=jdbc.queryForList("SELECT * FROM password_reset_codes WHERE account=? FOR UPDATE",account);
|
|
if(rows.isEmpty()) throw invalidResetCode();
|
|
var row=rows.getFirst();
|
|
java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant();
|
|
if(Boolean.TRUE.equals(row.get("consumed")) || !expiry.isAfter(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw invalidResetCode();
|
|
jdbc.update("UPDATE password_reset_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),resetDigest(account,code).getBytes(StandardCharsets.UTF_8))) throw invalidResetCode();
|
|
jdbc.update("UPDATE password_reset_codes SET consumed=true WHERE account=?",account);
|
|
return account;
|
|
}
|
|
private ApiException invalidResetCode() { return new ApiException("VERIFICATION_INVALID","验证码无效或已失效,请重新获取"); }
|
|
}
|