Coverage for models/auth.py: 87.70%

161 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 14:44 +0000

1""" 

2Authentication and user-related Pydantic models. 

3""" 

4 

5import re 

6 

7from pydantic import BaseModel, field_validator, model_validator 

8 

9from constants.passwords import validate_password 

10from constants.positions import Positions 

11from user_preferences import UserPreferences 

12 

13 

14class UserSignup(BaseModel): 

15 """Model for user signup requests.""" 

16 

17 username: str # Primary login credential (e.g., gabe_ifa_35) 

18 password: str 

19 email: str # Required for password recovery 

20 phone_number: str | None = None # Optional for SMS 

21 display_name: str | None = None 

22 invite_code: str | None = None 

23 

24 @field_validator("username") 

25 @classmethod 

26 def validate_username(cls, v): 

27 """Validate username format: 3-50 chars, alphanumeric and underscores only.""" 

28 if not re.match(r"^[a-zA-Z0-9_]{3,50}$", v): 

29 raise ValueError("Username must be 3-50 characters long and contain only letters, numbers, and underscores") 

30 return v.lower() # Store usernames in lowercase for consistency 

31 

32 @field_validator("email") 

33 @classmethod 

34 def validate_email(cls, v): 

35 """Validate and normalise the address. 

36 

37 Stored lowercase so it can be found again: the reset lookup 

38 normalises what it is given, and a mixed-case row would be 

39 unreachable by anyone typing it in a different case — including the 

40 person who chose it. Matches what the admin editor stores, so the 

41 same address lands identically whichever door it came through. 

42 """ 

43 if not v or "@" not in v: 43 ↛ 44line 43 didn't jump to line 44 because the condition on line 43 was never true

44 raise ValueError("A valid email address is required") 

45 return v.strip().lower() 

46 

47 @model_validator(mode="after") 

48 def enforce_password_policy(self): 

49 """Reject a password too weak to accept (SB-640). 

50 

51 A model validator rather than a field one so the username is 

52 available: the commonest weak password is the account's own name. 

53 """ 

54 validate_password(self.password, username=self.username) 

55 return self 

56 

57 

58class UserLogin(BaseModel): 

59 """Model for user login requests.""" 

60 

61 username: str # Changed from email 

62 password: str 

63 

64 @field_validator("username") 

65 @classmethod 

66 def validate_username(cls, v): 

67 """Ensure username is lowercase for lookup.""" 

68 return v.lower() 

69 

70 

71class UserProfile(BaseModel): 

72 """Model for user profile data.""" 

73 

74 display_name: str | None = None 

75 email: str | None = None 

76 role: str | None = None 

77 team_id: int | None = None 

78 player_number: int | None = None 

79 positions: Positions = None 

80 

81 # Photo fields 

82 photo_1_url: str | None = None 

83 photo_2_url: str | None = None 

84 photo_3_url: str | None = None 

85 profile_photo_slot: int | None = None 

86 # Customization fields 

87 overlay_style: str = "badge" 

88 primary_color: str = "#3B82F6" 

89 text_color: str = "#FFFFFF" 

90 accent_color: str = "#1D4ED8" 

91 # Telegram/Discord handles for channel access 

92 telegram_handle: str | None = None 

93 discord_handle: str | None = None 

94 # Partial update: only keys sent are applied, null clears (SB-1286) 

95 preferences: UserPreferences | None = None 

96 

97 

98class RoleUpdate(BaseModel): 

99 """Model for updating user roles.""" 

100 

101 user_id: str 

102 role: str 

103 team_id: int | None = None 

104 

105 

106class UserProfileUpdate(BaseModel): 

107 """Model for updating user profile information.""" 

108 

109 user_id: str 

110 username: str | None = None 

111 display_name: str | None = None 

112 email: str | None = None 

113 

114 

115class ForgotPasswordRequest(BaseModel): 

116 """Model for forgot-password requests. 

117 

118 Deliberately carries no email field. It used to: an account with none on 

119 file would accept one here and have a reset sent to it, which meant 

120 anyone who knew a username could take the account (SB-1129). The field is 

121 gone rather than validated, so nothing can reach for it again. 

122 """ 

123 

124 identifier: str # Username or email address 

125 

126 @field_validator("identifier") 

127 @classmethod 

128 def validate_identifier(cls, v: str) -> str: 

129 if not v or not v.strip(): 

130 raise ValueError("identifier must not be empty") 

131 return v.strip() 

132 

133 

134class ResetPasswordRequest(BaseModel): 

135 """Model for password-reset submission.""" 

136 

137 token: str 

138 new_password: str 

139 

140 @field_validator("new_password") 

141 @classmethod 

142 def enforce_password_policy(cls, v: str) -> str: 

143 """The same policy as signup (SB-640). 

144 

145 Reset used to accept six characters, which made it the way around 

146 whatever signup asked for. The username is not in this payload — the 

147 token identifies the account — so that half of the rule cannot be 

148 applied here. 

149 """ 

150 return validate_password(v) 

151 

152 

153class RefreshTokenRequest(BaseModel): 

154 """Model for refresh token requests.""" 

155 

156 refresh_token: str 

157 

158 

159class ProfilePhotoSlot(BaseModel): 

160 """Model for setting which photo slot is the profile picture.""" 

161 

162 slot: int 

163 

164 @field_validator("slot") 

165 @classmethod 

166 def validate_slot(cls, v): 

167 """Validate slot is 1, 2, or 3.""" 

168 if v not in (1, 2, 3): 

169 raise ValueError("Slot must be 1, 2, or 3") 

170 return v 

171 

172 

173class PlayerCustomization(BaseModel): 

174 """Model for player profile customization (colors, style, number, position, social media).""" 

175 

176 # Personal info 

177 first_name: str | None = None 

178 last_name: str | None = None 

179 hometown: str | None = None 

180 # Visual customization 

181 overlay_style: str | None = None 

182 primary_color: str | None = None 

183 text_color: str | None = None 

184 accent_color: str | None = None 

185 player_number: int | None = None # Jersey number (1-99) 

186 positions: Positions = None 

187 # Social media handles (username only, not full URLs) 

188 instagram_handle: str | None = None 

189 snapchat_handle: str | None = None 

190 tiktok_handle: str | None = None 

191 # Telegram/Discord handles for channel access 

192 telegram_handle: str | None = None 

193 discord_handle: str | None = None 

194 

195 @field_validator("instagram_handle", "snapchat_handle", "tiktok_handle") 

196 @classmethod 

197 def validate_social_handle(cls, v): 

198 """Validate social media handle format.""" 

199 if v is not None: 

200 # Remove @ if present 

201 v = v.lstrip("@") 

202 # Basic validation: alphanumeric, underscores, periods, max 30 chars 

203 if len(v) > 30: 

204 raise ValueError("Handle must be 30 characters or less") 

205 if v and not re.match(r"^[a-zA-Z0-9_.]+$", v): 

206 raise ValueError("Handle can only contain letters, numbers, underscores, and periods") 

207 return v 

208 

209 @field_validator("overlay_style") 

210 @classmethod 

211 def validate_overlay_style(cls, v): 

212 """Validate overlay style.""" 

213 if v is not None and v not in ("badge", "jersey", "caption", "none"): 

214 raise ValueError("overlay_style must be 'badge', 'jersey', 'caption', or 'none'") 

215 return v 

216 

217 @field_validator("primary_color", "text_color", "accent_color") 

218 @classmethod 

219 def validate_color(cls, v): 

220 """Validate hex color format.""" 

221 if v is not None and not re.match(r"^#[0-9A-Fa-f]{6}$", v): 

222 raise ValueError("Color must be a valid hex color (e.g., #3B82F6)") 

223 return v 

224 

225 

226class PlayerHistoryCreate(BaseModel): 

227 """Model for creating a player team history entry.""" 

228 

229 team_id: int 

230 season_id: int 

231 jersey_number: int | None = None 

232 positions: Positions = None 

233 notes: str | None = None 

234 is_current: bool = False 

235 age_group_id: int | None = None 

236 

237 @field_validator("jersey_number") 

238 @classmethod 

239 def validate_jersey_number(cls, v): 

240 """Validate jersey number is 1-99.""" 

241 if v is not None and (v < 1 or v > 99): 

242 raise ValueError("Jersey number must be between 1 and 99") 

243 return v 

244 

245 

246class PlayerHistoryUpdate(BaseModel): 

247 """Model for updating a player team history entry.""" 

248 

249 jersey_number: int | None = None 

250 positions: Positions = None 

251 notes: str | None = None 

252 is_current: bool | None = None 

253 

254 @field_validator("jersey_number") 

255 @classmethod 

256 def validate_jersey_number(cls, v): 

257 """Validate jersey number is 1-99.""" 

258 if v is not None and (v < 1 or v > 99): 

259 raise ValueError("Jersey number must be between 1 and 99") 

260 return v 

261 

262 

263class AdminPlayerUpdate(BaseModel): 

264 """Model for admin updating a player's profile info.""" 

265 

266 display_name: str | None = None 

267 player_number: int | None = None 

268 positions: Positions = None 

269 

270 @field_validator("player_number") 

271 @classmethod 

272 def validate_player_number(cls, v): 

273 """Validate player number is 1-99.""" 

274 if v is not None and (v < 1 or v > 99): 

275 raise ValueError("Player number must be between 1 and 99") 

276 return v 

277 

278 

279class AdminPlayerTeamAssignment(BaseModel): 

280 """Model for admin assigning a player to a team.""" 

281 

282 team_id: int 

283 season_id: int 

284 jersey_number: int | None = None 

285 start_date: str | None = None 

286 is_current: bool = True 

287 age_group_id: int | None = None 

288 

289 @field_validator("jersey_number") 

290 @classmethod 

291 def validate_jersey_number(cls, v): 

292 """Validate jersey number is 1-99.""" 

293 if v is not None and (v < 1 or v > 99): 

294 raise ValueError("Jersey number must be between 1 and 99") 

295 return v 

296 

297 

298class AdminPlayerTeamEnd(BaseModel): 

299 """Model for ending a player's team assignment.""" 

300 

301 end_date: str