forked from lichess-org/lila
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAuth.scala
225 lines (203 loc) · 7.94 KB
/
Auth.scala
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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package controllers
import play.api.data._, Forms._
import play.api.i18n.Messages.Implicits._
import play.api.libs.json._
import play.api.mvc._, Results._
import play.api.Play.current
import lila.api.Context
import lila.app._
import lila.common.{ LilaCookie, HTTPRequest }
import lila.user.{ UserRepo, User => UserModel }
import views._
object Auth extends LilaController {
private def env = Env.security
private def api = env.api
private def forms = env.forms
private def mobileUserOk(u: UserModel): Fu[Result] =
lila.game.GameRepo urgentGames u map { povs =>
Ok {
Env.user.jsonView(u) ++ Json.obj(
"nowPlaying" -> JsArray(povs take 20 map Env.api.lobbyApi.nowPlaying))
}
}
private def authenticateUser(u: UserModel)(implicit ctx: Context): Fu[Result] = {
implicit val req = ctx.req
u.ipBan.fold(
Env.security.firewall.blockIp(req.remoteAddress) inject BadRequest("blocked by firewall"),
api.saveAuthentication(u.id, ctx.mobileApiVersion) flatMap { sessionId =>
negotiate(
html = Redirect {
get("referrer").filter(_.nonEmpty) orElse req.session.get(api.AccessUri) getOrElse routes.Lobby.home.url
}.fuccess,
api = _ => mobileUserOk(u)
) map {
_ withCookies LilaCookie.withSession { session =>
session + ("sessionId" -> sessionId) - api.AccessUri
}
}
} recoverWith authRecovery
)
}
private def authRecovery(implicit ctx: Context): PartialFunction[Throwable, Fu[Result]] = {
case lila.security.Api.AuthFromTorExitNode => noTorResponse
case lila.security.Api.MustConfirmEmail(userId) => UserRepo byId userId map {
case Some(user) => BadRequest(html.auth.checkYourEmail(user))
case None => BadRequest
}
}
def login = Open { implicit ctx =>
if (Env.security.tor isExitNode ctx.req.remoteAddress)
Unauthorized(html.auth.tor()).fuccess
else {
val referrer = get("referrer")
Ok(html.auth.login(api.loginForm, referrer)).fuccess
}
}
def authenticate = OpenBody { implicit ctx =>
Firewall {
implicit val req = ctx.body
api.loginForm.bindFromRequest.fold(
err => negotiate(
html = Unauthorized(html.auth.login(err, get("referrer"))).fuccess,
api = _ => Unauthorized(errorsAsJson(err)).fuccess
),
_.fold(InternalServerError("Authentication error").fuccess)(authenticateUser)
)
}
}
def logout = Open { implicit ctx =>
implicit val req = ctx.req
req.session get "sessionId" foreach lila.security.Store.delete
negotiate(
html = fuccess(Redirect(routes.Main.mobile)),
api = apiVersion => Ok(Json.obj("ok" -> true)).fuccess
) map (_ withCookies LilaCookie.newSession)
}
def signup = Open { implicit ctx =>
if (Env.security.tor isExitNode ctx.req.remoteAddress)
Unauthorized(html.auth.tor()).fuccess
else {
forms.signup.websiteWithCaptcha map {
case (form, captcha) => Ok(html.auth.signup(form, captcha, env.RecaptchaPublicKey))
}
}
}
def signupPost = OpenBody { implicit ctx =>
implicit val req = ctx.body
Firewall {
negotiate(
html = forms.signup.website.bindFromRequest.fold(
err => forms.anyCaptcha map { captcha =>
BadRequest(html.auth.signup(err, captcha, env.RecaptchaPublicKey))
},
data => env.recaptcha.verify(~data.recaptchaResponse, req).flatMap {
case false => forms.signup.websiteWithCaptcha map {
case (form, captcha) => BadRequest(html.auth.signup(form fill data, captcha, env.RecaptchaPublicKey))
}
case true =>
lila.mon.user.register.website()
val email = env.emailAddress.validate(data.email) err s"Invalid email ${data.email}"
UserRepo.create(data.username, data.password, email.some, ctx.blindMode, none)
.flatten(s"No user could be created for ${data.username}")
.map(_ -> email).flatMap {
case (user, email) => env.emailConfirm.send(user, email) >> {
if (env.emailConfirm.effective) Redirect(routes.Auth.checkYourEmail(user.username)).fuccess
else saveAuthAndRedirect(user)
}
}
}),
api = apiVersion => forms.signup.mobile.bindFromRequest.fold(
err => fuccess(BadRequest(jsonError(errorsAsJson(err)))),
data => {
lila.mon.user.register.mobile()
val email = data.email flatMap env.emailAddress.validate
UserRepo.create(data.username, data.password, email, false, apiVersion.some)
.flatten(s"No user could be created for ${data.username}") flatMap authenticateUser
}
)
)
}
}
def checkYourEmail(name: String) = Open { implicit ctx =>
OptionOk(UserRepo named name) { user =>
html.auth.checkYourEmail(user)
}
}
def signupConfirmEmail(token: String) = Open { implicit ctx =>
Env.security.emailConfirm.confirm(token) flatMap {
_.fold(notFound)(saveAuthAndRedirect)
}
}
private def saveAuthAndRedirect(user: UserModel)(implicit ctx: Context) = {
implicit val req = ctx.req
api.saveAuthentication(user.id, ctx.mobileApiVersion) map { sessionId =>
Redirect(routes.User.show(user.username)) withCookies LilaCookie.session("sessionId", sessionId)
} recoverWith authRecovery
}
private def noTorResponse(implicit ctx: Context) = negotiate(
html = Unauthorized(html.auth.tor()).fuccess,
api = _ => Unauthorized(jsonError("Can't login from Tor, sorry!")).fuccess)
def setFingerprint(fp: String, ms: Int) = Auth { ctx =>
me =>
api.setFingerprint(ctx.req, fp) flatMap {
_ ?? { hash =>
!me.lame ?? {
api.recentUserIdsByFingerprint(hash).map(_.filter(me.id!=)) flatMap {
case otherIds if otherIds.size >= 2 => UserRepo countEngines otherIds flatMap {
case nb if nb >= 2 && nb >= otherIds.size / 2 => Env.report.api.autoCheatPrintReport(me.id)
case _ => funit
}
case _ => funit
}
}
}
} inject Ok
}
def passwordReset = Open { implicit ctx =>
forms.passwordResetWithCaptcha map {
case (form, captcha) => Ok(html.auth.passwordReset(form, captcha))
}
}
def passwordResetApply = OpenBody { implicit ctx =>
implicit val req = ctx.body
forms.passwordReset.bindFromRequest.fold(
err => forms.anyCaptcha map { captcha =>
BadRequest(html.auth.passwordReset(err, captcha, false.some))
},
data => {
val email = env.emailAddress.validate(data.email) | data.email
UserRepo enabledByEmail email flatMap {
case Some(user) =>
Env.security.passwordReset.send(user, email) inject Redirect(routes.Auth.passwordResetSent(data.email))
case _ => forms.passwordResetWithCaptcha map {
case (form, captcha) => BadRequest(html.auth.passwordReset(form, captcha, false.some))
}
}
}
)
}
def passwordResetSent(email: String) = Open { implicit ctx =>
fuccess {
Ok(html.auth.passwordResetSent(email))
}
}
def passwordResetConfirm(token: String) = Open { implicit ctx =>
Env.security.passwordReset confirm token flatMap {
case Some(user) =>
fuccess(html.auth.passwordResetConfirm(user, token, forms.passwdReset, none))
case _ => notFound
}
}
def passwordResetConfirmApply(token: String) = OpenBody { implicit ctx =>
Env.security.passwordReset confirm token flatMap {
case Some(user) =>
implicit val req = ctx.body
FormFuResult(forms.passwdReset) { err =>
fuccess(html.auth.passwordResetConfirm(user, token, err, false.some))
} { data =>
UserRepo.passwd(user.id, data.newPasswd1) >> authenticateUser(user)
}
case _ => notFound
}
}
}