public HttpResponseMessage PostLoginUser(UserModel model) { return this.PerformOperationAndHandleExceptions(() => { var context = new BankContext(); using (context) { var usernameToLower = model.Username.ToLower(); var entity = context.Users.SingleOrDefault(u => u.Username == usernameToLower && u.AuthCode == model.AuthCode); if (entity == null) { var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid username or password"); throw new HttpResponseException(errResponse); } entity.SessionKey = entity.Id.ToString(); //this.GenerateSessionKey(entity.Id); context.SaveChanges(); var responseModel = new UserLoggedModel() { Username = entity.Username, SessionKey = entity.SessionKey }; var response = this.Request.CreateResponse(HttpStatusCode.Accepted, responseModel); return response; } }); }
public HttpResponseMessage Login(UserModel model) { var responseMsg = this.ExceptionHandling( () => { var context = new BankContext(); using (context) { this.ValidateUsername(model.Username); this.ValidateAuthCode(model.AuthCode); var usernameToLower = model.Username.ToLower(); var user = context.Users.FirstOrDefault( usr => usr.Username == usernameToLower && usr.AuthCode == model.AuthCode); if (user == null) { throw new InvalidOperationException("Invalid username or password!"); } if (user.SessionKey == null) { user.SessionKey = this.GenerateSessionKey(user.Id); context.SaveChanges(); } var loggedModel = new LoggedUserModel() { Username = user.Username, SessionKey = user.SessionKey }; var response = this.Request.CreateResponse(HttpStatusCode.Created, loggedModel); return response; } }); return responseMsg; }
public HttpResponseMessage PostRegisterUser(UserModel model) { return this.PerformOperationAndHandleExceptions(() => { var usernameToLower = model.Username.ToLower(); var context = new BankContext(); using (context) { var entity = context.Users.FirstOrDefault(u => u.Username == usernameToLower); if (entity != null) { string responseMessage = "Username already taken"; HttpResponseMessage errResponse = this.Request.CreateErrorResponse(HttpStatusCode.Conflict, responseMessage); throw new HttpResponseException(errResponse); } var user = new User() { Username = model.Username.ToLower(), AuthCode = model.AuthCode }; context.Users.Add(user); context.SaveChanges(); return this.PostLoginUser(model); } }); }