1
|
|
|
import { Float } from "react-native/Libraries/Types/CodegenTypes"; |
2
|
|
|
import config from "../config/config.json"; |
3
|
|
|
import * as EmailValidator from 'email-validator'; |
4
|
|
|
import { API_KEY } from "@env"; |
5
|
|
|
import storage from './storage'; |
6
|
|
|
|
7
|
|
|
const authModel = { |
8
|
|
|
register: async function register(user: object): Promise<Object> { |
9
|
|
|
user['api_key'] = API_KEY; |
10
|
|
|
|
11
|
|
|
const response = await fetch(`${config.base_url}users`, { |
12
|
|
|
method: 'POST', |
13
|
|
|
body: JSON.stringify(user), |
14
|
|
|
headers: { |
15
|
|
|
'content-type': 'application/json' |
16
|
|
|
}, |
17
|
|
|
}); |
18
|
|
|
|
19
|
|
|
const result = await response.json(); |
20
|
|
|
if (Object.prototype.hasOwnProperty.call(result, 'errors')) { |
21
|
|
|
return { |
22
|
|
|
title: result.errors.title, |
23
|
|
|
message: result.errors.detail, |
24
|
|
|
type: "danger", |
25
|
|
|
}; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
return { |
29
|
|
|
title: "Login", |
30
|
|
|
message: result.data.message, |
31
|
|
|
type: "success", |
32
|
|
|
}; |
33
|
|
|
}, |
34
|
|
|
|
35
|
|
|
login: async function login(user: object): Promise<Object> { |
36
|
|
|
user['api_key'] = API_KEY; |
37
|
|
|
|
38
|
|
|
const response = await fetch(`${config.base_url}auth/login/server/user`, { |
39
|
|
|
method: 'POST', |
40
|
|
|
body: JSON.stringify(user), |
41
|
|
|
headers: { |
42
|
|
|
'content-type': 'application/json' |
43
|
|
|
}, |
44
|
|
|
}); |
45
|
|
|
|
46
|
|
|
const result = await response.json(); |
47
|
|
|
|
48
|
|
|
if (Object.prototype.hasOwnProperty.call(result, 'errors')) { |
49
|
|
|
return { |
50
|
|
|
title: result.errors.title, |
51
|
|
|
message: result.errors.detail, |
52
|
|
|
type: "danger", |
53
|
|
|
}; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
//Store userdata |
57
|
|
|
const userData = result['data']['user']; |
58
|
|
|
|
59
|
|
|
await storage.storeUser(userData); |
60
|
|
|
|
61
|
|
|
|
62
|
|
|
//Store token |
63
|
|
|
const token = result['data']['token']; |
64
|
|
|
console.log(token); |
65
|
|
|
|
66
|
|
|
await storage.storeToken(token); |
67
|
|
|
|
68
|
|
|
return { |
69
|
|
|
title: "Login", |
70
|
|
|
message: result.data.message, |
71
|
|
|
type: "success", |
72
|
|
|
}; |
73
|
|
|
}, |
74
|
|
|
|
75
|
|
|
checkEmail: function checkEmail(email: string): Boolean { |
76
|
|
|
return EmailValidator.validate(email); |
77
|
|
|
}, |
78
|
|
|
|
79
|
|
|
test: function test() { |
80
|
|
|
console.log( |
81
|
|
|
'authmodel' |
82
|
|
|
); |
83
|
|
|
}, |
84
|
|
|
|
85
|
|
|
logout: async function logout(): Promise<void> { |
86
|
|
|
await storage.deleteToken(); |
87
|
|
|
}, |
88
|
|
|
}; |
89
|
|
|
|
90
|
|
|
export default authModel; |
91
|
|
|
|