-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathauth.service(coffee).coffee
149 lines (113 loc) · 2.66 KB
/
auth.service(coffee).coffee
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
'use strict'
angular.module '<%= scriptAppName %>'
.factory 'Auth', ($location, $rootScope, $http, User, $localStorage, $q) ->
currentUser = if $localStorage.token then User.get() else {}
###
Authenticate user and save token
@param {Object} user - login info
@param {Function} callback - optional
@return {Promise}
###
login: (user, callback) ->
deferred = $q.defer()
$http.post '/auth/local',
email: user.email
password: user.password
.success (data) ->
$localStorage.token = data.token
currentUser = User.get()
deferred.resolve data
callback?()
.error (err) =>
@logout()
deferred.reject err
callback? err
deferred.promise
###
Delete access token and user info
@param {Function}
###
logout: ->
delete $localStorage.token
currentUser = {}
return
###
Create a new user
@param {Object} user - user info
@param {Function} callback - optional
@return {Promise}
###
createUser: (user, callback) ->
User.save user,
(data) ->
$localStorage.token = data.token
currentUser = User.get()
callback? user
, (err) =>
@logout()
callback? err
.$promise
###
Change password
@param {String} oldPassword
@param {String} newPassword
@param {Function} callback - optional
@return {Promise}
###
changePassword: (oldPassword, newPassword, callback) ->
User.changePassword
id: currentUser._id
,
oldPassword: oldPassword
newPassword: newPassword
, (user) ->
callback? user
, (err) ->
callback? err
.$promise
###
Gets all available info on authenticated user
@return {Object} user
###
getCurrentUser: ->
currentUser
###
Check if a user is logged in synchronously
@return {Boolean}
###
isLoggedIn: ->
currentUser.hasOwnProperty 'role'
###
Waits for currentUser to resolve before checking if user is logged in
###
isLoggedInAsync: (callback) ->
if currentUser.hasOwnProperty '$promise'
currentUser.$promise.then ->
callback? true
return
.catch ->
callback? false
return
else
callback? currentUser.hasOwnProperty 'role'
###
Check if a user is an admin
@return {Boolean}
###
isAdmin: ->
currentUser.role is 'admin'
###
Get auth token
###
getToken: ->
$localStorage.token
###
Set session token
@param {String} session token
@return {Promise}
###
setSessionToken: (sessionToken, callback) ->
cb = callback || angular.noop;
$localStorage.token = sessionToken
currentUser = User.get(cb)
return