A social knowledge tool for researchers built on ATProto
1import { Result, err, ok } from 'src/shared/core/Result';
2import { IUserRepository } from '../../domain/repositories/IUserRepository';
3import {
4 IUserAuthenticationService,
5 AuthenticationResult,
6} from '../../domain/services/IUserAuthenticationService';
7import { DID } from '../../domain/value-objects/DID';
8import { Handle } from '../../domain/value-objects/Handle';
9import { User } from '../../domain/User';
10
11export class UserAuthenticationService implements IUserAuthenticationService {
12 constructor(private userRepository: IUserRepository) {}
13
14 async validateUserCredentials(
15 did: DID,
16 handle?: Handle,
17 ): Promise<Result<AuthenticationResult>> {
18 try {
19 // Try to find existing user
20 const userResult = await this.userRepository.findByDID(did);
21
22 if (userResult.isErr()) {
23 return err(userResult.error);
24 }
25
26 const existingUser = userResult.value;
27
28 // If user exists, update handle if provided
29 if (existingUser) {
30 if (
31 handle &&
32 (!existingUser.handle || existingUser.handle.value !== handle.value)
33 ) {
34 existingUser.updateHandle(handle);
35 }
36
37 return ok({
38 user: existingUser,
39 isNewUser: false,
40 });
41 }
42
43 // Create new user
44 const newUserResult = User.createNew(did, handle);
45
46 if (newUserResult.isErr()) {
47 return err(newUserResult.error);
48 }
49
50 return ok({
51 user: newUserResult.value,
52 isNewUser: true,
53 });
54 } catch (error: any) {
55 return err(error);
56 }
57 }
58}