package com.yau.digitalrmb.institutionidentity.application; import com.yau.digitalrmb.security.context.JwtUser; import com.yau.digitalrmb.security.application.CurrentUser; import com.yau.digitalrmb.shared.api.ErrorCode; import com.yau.digitalrmb.shared.exception.BusinessException; public class InstitutionKeySubject { private final String userId; private final long schoolId; private final long classId; private final String userName; private final String phone; public InstitutionKeySubject(String userId, long schoolId, long classId) { this(userId, schoolId, classId, null, null); } public InstitutionKeySubject(String userId, long schoolId, long classId, String userName, String phone) { this.userId = userId; this.schoolId = schoolId; this.classId = classId; this.userName = userName; this.phone = phone; } public static InstitutionKeySubject from(JwtUser jwtUser) { return new InstitutionKeySubject(jwtUser.getUserId(), requiredLong(jwtUser.getSchoolId(), "schoolId"), requiredLong(jwtUser.getClassId(), "classId"), jwtUser.getUserName(), jwtUser.getPhone()); } public static InstitutionKeySubject from(CurrentUser currentUser) { if (currentUser == null || currentUser.getUserId() == null || currentUser.getUserId().trim().isEmpty()) { throw new BusinessException(ErrorCode.UNAUTHORIZED, "当前用户ID不能为空"); } return new InstitutionKeySubject(currentUser.getUserId(), requiredLong(currentUser.getSchoolId(), "schoolId"), requiredLong(currentUser.getClassId(), "classId")); } private static long requiredLong(String value, String claim) { if (value == null) { throw new BusinessException(ErrorCode.UNAUTHORIZED, "Token缺少" + claim); } try { return Long.parseLong(value); } catch (NumberFormatException exception) { throw new BusinessException(ErrorCode.UNAUTHORIZED, "Token中的" + claim + "格式不正确"); } } public String getUserId() { return userId; } public long getSchoolId() { return schoolId; } public long getClassId() { return classId; } public String getUserName() { return userName; } public String getPhone() { return phone; } }