public HttpResponseMessage LoginUser(UserModel model) { return this.ExecuteOperationAndHandleExceptions(() => { //this.ValidateUser(model); if (model == null) { throw new FormatException("invalid username and/or password"); } this.ValidateAuthCode(model.AuthCode); this.ValidateUsername(model.Username); var context = new RecipeContext(); var username = (model.Username).ToLower(); var user = context.Users.FirstOrDefault(u => u.UserName == username); if (user == null) { throw new InvalidOperationException("Invalid username"); } if (user.AuthenticationCode != model.AuthCode) { throw new InvalidOperationException("Invalid password"); } if (user.AccessToken == null) { user.AccessToken = this.GenerateAccessToken(user.UserId); context.SaveChanges(); } var responseModel = new LoginResponseModel() { Id = user.UserId, Username = user.UserName, AccessToken = user.AccessToken }; var response = this.Request.CreateResponse(HttpStatusCode.OK, responseModel); return response; }); }
public HttpResponseMessage RegisterUser(UserModel model) { return this.ExecuteOperationAndHandleExceptions(() => { this.ValidateUser(model); var context = new RecipeContext(); var dbUser = GetUserByUsername(model, context); if (dbUser != null) { throw new InvalidOperationException("This user already exists in the database"); } dbUser = new User() { UserName = model.Username, AuthenticationCode = model.AuthCode }; context.Users.Add(dbUser); context.SaveChanges(); var responseModel = new RegisterUserResponseModel() { Id = dbUser.UserId, Username = dbUser.UserName, }; var response = this.Request.CreateResponse(HttpStatusCode.Created, responseModel); return response; }); }
private void ValidateUser(UserModel userModel) { if (userModel == null) { throw new FormatException("Username and/or password are invalid"); } this.ValidateUsername(userModel.Username); this.ValidateAuthCode(userModel.AuthCode); }
private User GetUserByUsername(UserModel model, RecipeContext context) { var usernameToLower = model.Username.ToLower(); var dbUser = context.Users.FirstOrDefault(u => u.UserName == usernameToLower); return dbUser; }