File size: 1,423 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import hashPii from './hash-pii';

/**
 * Module variables
 */
let _currentUser: CurrentUser;

export interface SetCurrentUserParams {
	ID: string;
	username: string;
	email: string;
	localeSlug: string;
}

export interface CurrentUserHashedPii {
	ID: string;
	username: string;
	email: string;
}

export interface CurrentUser {
	ID: number;
	username: string;
	email: string;
	hashedPii: CurrentUserHashedPii;
	localeSlug: string;
}

/**
 * Gets current user.
 * @returns Current user.
 */
export function getCurrentUser(): CurrentUser {
	return _currentUser;
}

/**
 * Sets current user, (stored in javascript memory).
 * @param currentUser the user data for the current user
 * @returns Current user.
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function setCurrentUser( currentUser: SetCurrentUserParams ): CurrentUser | undefined {
	if (
		! currentUser.ID ||
		isNaN( parseInt( currentUser.ID, 10 ) ) ||
		! currentUser.username ||
		! currentUser.email
	) {
		return; // Invalid user data.
	}
	_currentUser = {
		ID: parseInt( currentUser.ID, 10 ),
		username: currentUser.username,
		email: currentUser.email,
		localeSlug: currentUser.localeSlug,
		hashedPii: {
			ID: hashPii( currentUser.ID ),
			username: hashPii( currentUser.username.toLowerCase().replace( /\s/g, '' ) ),
			email: hashPii( currentUser.email.toLowerCase().replace( /\s/g, '' ) ),
		},
	};
	return _currentUser;
}