async Task <HttpResponseMessage> login(User userRequest) { LoginInfos loginInfos = new LoginInfos(); HttpResponseMessage response = new HttpResponseMessage(); HttpResponseMessage unauthorized = Request.CreateErrorResponse(HttpStatusCode.Forbidden, new UnauthorizedAccessException()); if (loginInfos.userExists(userRequest)) { User userDB = loginInfos.getUserFromRequest(userRequest); string passwordDB = userDB.password; int nbTentativesDB = userDB.nbTentatives; var filter = Builders <User> .Filter.Eq(u => u.login, userDB.login); if (nbTentativesDB == 5) { return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, new Exception("Nombre de tentatives > 5. Réinitialisez le mot de passe."))); } if (!loginInfos.isGoodPassword(userRequest.password, userDB.password)) { userDB.nbTentatives++; await _collection.ReplaceOneAsync(filter, userDB); return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, new Exception("Mot de passe erroné, Nombre de tentatives restantes : " + (4 - nbTentativesDB).ToString() + "."))); } userDB.nbTentatives = 0; await _collection.ReplaceOneAsync(filter, userDB); response.Headers.AddCookies(new CookieHeaderValue[] { createCookie("timeout", DateTime.Now.AddHours(4).ToString()), createCookie("login", userRequest.login) }); response.Content = new StringContent(userRequest.login + " connecté avec succès."); response.StatusCode = HttpStatusCode.OK; return(response); } return(unauthorized); }
HttpResponseMessage signin(User userRequest) { LoginInfos loginInfos = new LoginInfos(); HttpResponseMessage response = new HttpResponseMessage(); if (loginInfos.userExists(userRequest)) { response.Content = new StringContent("Le user " + userRequest.login + " est déjà connu dans la base de données."); response.StatusCode = HttpStatusCode.OK; } else { response.Content = new StringContent("L'utilisateur " + userRequest.login + " a été créé."); response.StatusCode = HttpStatusCode.Created; userRequest._id = Guid.NewGuid().ToString(); userRequest.nbTentatives = 0; userRequest.password = loginInfos.encrypt(userRequest.password); _collection.InsertOne(userRequest); } return(response); }