public HttpResponseMessage LoginUser([FromBody] UserUnloggedModel userModel) { var responseMessage = this.PerformOperationAndHandleExceptions(() => { var context = new BookstoreContext(); using (context) { if (userModel == null) { throw new ServerErrorException("User credentials not passed correctly", "invalid_credentials"); } this.ValidateUsername(userModel.Username); this.ValidateAuthCode(userModel.AuthCode); var lowerCaseUsername = userModel.Username.ToLower(); var existingUser = context.Users.SingleOrDefault(u => u.Username == lowerCaseUsername && u.AuthCode == userModel.AuthCode); if (existingUser == null) { throw new ServerErrorException("User with that username or password does not exist.", "user_does_not_exist"); } if (existingUser.IsActive == false) { throw new ServerErrorException("User is not active.", "user_is_not_active"); } if (existingUser.SessionKey == null) { var sessionKey = this.GenerateSessionKey(existingUser.Id); existingUser.SessionKey = sessionKey; context.SaveChanges(); } var userReturnModel = new UserLoggedModel(); userReturnModel.SessionKey = existingUser.SessionKey; userReturnModel.DisplayName = existingUser.Username; return(Request.CreateResponse(HttpStatusCode.Created, userReturnModel)); } }); return(responseMessage); }
public HttpResponseMessage RegisterUser([FromBody] UserUnloggedModel userModel) { var responseMessage = this.PerformOperationAndHandleExceptions(() => { var context = new BookstoreContext(); using (context) { if (userModel == null) { throw new ServerErrorException("User credentials not passed correctly", "invalid_credentials"); } this.ValidateUsername(userModel.Username); this.ValidateAuthCode(userModel.AuthCode); var lowerCaseUsername = userModel.Username.ToLower(); var existingUser = context.Users.SingleOrDefault(u => u.Username == lowerCaseUsername); if (existingUser != null) { throw new ServerErrorException("User with that username or nickname already exists.", "user_exists"); } var newUser = new User(); newUser.Username = lowerCaseUsername; newUser.AuthCode = userModel.AuthCode; newUser.IsActive = true; context.Users.Add(newUser); context.SaveChanges(); var sessionKey = this.GenerateSessionKey(newUser.Id); newUser.SessionKey = sessionKey; context.SaveChanges(); var userReturnModel = new UserLoggedModel(); userReturnModel.SessionKey = newUser.SessionKey; userReturnModel.DisplayName = newUser.Username; return(Request.CreateResponse(HttpStatusCode.Created, userReturnModel)); } }); return(responseMessage); }