summaryrefslogtreecommitdiff
path: root/web/src/services/UserInfoTOTPConfiguration.ts
blob: 5bfd6a260588570d771c286888ef8e8f5b7550dc (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import axios from "axios";

import {
    TOTPAlgorithmPayload,
    TOTPDigits,
    TOTPOptions,
    UserInfoTOTPConfiguration,
    toEnum,
} from "@models/TOTPConfiguration";
import {
    AuthenticationOKResponse,
    CompleteTOTPSignInPath,
    ServiceResponse,
    TOTPConfigurationPath,
    TOTPRegistrationPath,
    validateStatusAuthentication,
} from "@services/Api";
import { Get } from "@services/Client";

export interface UserInfoTOTPConfigurationPayload {
    created_at: string;
    last_used_at?: string;
    issuer: string;
    algorithm: TOTPAlgorithmPayload;
    digits: TOTPDigits;
    period: number;
}

function toUserInfoTOTPConfiguration(payload: UserInfoTOTPConfigurationPayload): UserInfoTOTPConfiguration {
    return {
        created_at: new Date(payload.created_at),
        last_used_at: payload.last_used_at ? new Date(payload.last_used_at) : undefined,
        issuer: payload.issuer,
        algorithm: toEnum(payload.algorithm),
        digits: payload.digits,
        period: payload.period,
    };
}

export async function getUserInfoTOTPConfiguration(): Promise<UserInfoTOTPConfiguration> {
    const res = await Get<UserInfoTOTPConfigurationPayload>(TOTPConfigurationPath);

    return toUserInfoTOTPConfiguration(res);
}

export async function getUserInfoTOTPConfigurationOptional(): Promise<UserInfoTOTPConfiguration | null> {
    const res = await axios.get<ServiceResponse<UserInfoTOTPConfigurationPayload>>(TOTPConfigurationPath, {
        validateStatus: function (status) {
            return status < 300 || status === 404;
        },
    });

    if (res === null || res.status === 404 || res.data.status === "KO") {
        return null;
    }

    return toUserInfoTOTPConfiguration(res.data.data);
}

export interface TOTPOptionsPayload {
    algorithm: TOTPAlgorithmPayload;
    algorithms: TOTPAlgorithmPayload[];
    length: TOTPDigits;
    lengths: TOTPDigits[];
    period: number;
    periods: number[];
}

export async function getTOTPOptions(): Promise<TOTPOptions> {
    const res = await Get<TOTPOptionsPayload>(TOTPRegistrationPath);

    return {
        algorithm: toEnum(res.algorithm),
        algorithms: res.algorithms.map((alg) => toEnum(alg)),
        length: res.length,
        lengths: res.lengths,
        period: res.period,
        periods: res.periods,
    };
}

export async function deleteUserTOTPConfiguration() {
    return axios<AuthenticationOKResponse>({
        method: "DELETE",
        url: CompleteTOTPSignInPath,
        validateStatus: validateStatusAuthentication,
    });
}