public async Task <HttpResponseMessage> InitiateComment([FromBody] InitiateCommentViewModel parameters) { try { #region Parameters validation // Parameters haven't been initialized. if (parameters == null) { parameters = new InitiateCommentViewModel(); Validate(parameters); } //Request parameters are invalid if (!ModelState.IsValid) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState)); } #endregion #region Request identity search // Search account which sends the current request. var account = _identityService.FindAccount(Request.Properties); if (account == null) { throw new Exception("No account information is attached into current request."); } #endregion #region Comment initialization var comment = new Comment(); comment.OwnerIndex = account.Id; comment.PostIndex = parameters.PostIndex; comment.Content = parameters.Content; comment.Created = _timeService.DateTimeUtcToUnix(DateTime.UtcNow); //Add category record UnitOfWork.RepositoryComments.Insert(comment); // Save changes into database. await UnitOfWork.CommitAsync(); #endregion return(Request.CreateResponse(HttpStatusCode.OK, comment)); } catch (Exception exception) { _log.Error(exception.Message, exception); return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } }
public IActionResult Login([FromBody] LoginViewModel info) { if (info == null) { info = new LoginViewModel(); TryValidateModel(info); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = _userRepository .Get().FirstOrDefault(x => x.Email.Equals(info.Email, StringComparison.InvariantCultureIgnoreCase)); if (user == null) { return(NotFound()); } var claims = new List <Claim>(); claims.Add(new Claim(ClaimValueTypes.Email, user.Email)); claims.Add(new Claim(ClaimValueTypes.KeyInfo, user.Id.ToString())); // Find current time on the system. var systemTime = DateTime.Now; var jwtExpiration = systemTime.AddSeconds(_jwtOption.LifeTime); // Write a security token. var jwtSecurityToken = new JwtSecurityToken(_jwtOption.Issuer, _jwtOption.Audience, claims, null, jwtExpiration, _jwtOption.SigningCredentials); // Initiate token handler which is for generating token code. var jwtSecurityTokenHandler = new JwtSecurityTokenHandler(); jwtSecurityTokenHandler.WriteToken(jwtSecurityToken); // Initialize jwt response. var jwt = new JwtResponse(); jwt.Code = jwtSecurityTokenHandler.WriteToken(jwtSecurityToken); jwt.LifeTime = _jwtOption.LifeTime; jwt.Expiration = _timeService.DateTimeUtcToUnix(jwtExpiration); return(Ok(jwt)); }
public async Task <HttpResponseMessage> InitiateCommentReport( [FromBody] InitiateCommentReportViewModel parameters) { try { #region Parameters validation // Parameters haven't been initialized. if (parameters == null) { parameters = new InitiateCommentReportViewModel(); Validate(parameters); } // Parameters are invalid. if (!ModelState.IsValid) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState)); } #endregion #region Comment find // Comment find conditions build. var findCommentViewModel = new SearchCommentViewModel(); findCommentViewModel.Id = parameters.CommentIndex; // Search all comments from database. var comments = UnitOfWork.RepositoryComments.Search(); comments = UnitOfWork.RepositoryComments.Search(comments, findCommentViewModel); // Search the first matched comment. var comment = await comments.FirstOrDefaultAsync(); if (comment == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.CommentNotFound)); } #endregion #region Request identity search // Search account which sends the current request. var account = _identityService.FindAccount(Request.Properties); if (account == null) { throw new Exception("No account information is attached into current request."); } #endregion #region Record initialization var commentReport = new CommentReport(); commentReport.CommentIndex = comment.Id; commentReport.CommentOwnerIndex = comment.OwnerIndex; commentReport.CommentReporterIndex = account.Id; commentReport.Body = comment.Content; commentReport.Reason = parameters.Reason; commentReport.Created = _timeService.DateTimeUtcToUnix(DateTime.UtcNow); // Save record into database. commentReport = UnitOfWork.RepositoryCommentReports.Insert(commentReport); // Commit changes to database. await UnitOfWork.CommitAsync(); #endregion return(Request.CreateResponse(HttpStatusCode.OK, commentReport)); } catch (Exception exception) { _log.Error(exception.Message, exception); return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } }
public async Task <HttpResponseMessage> InitiatePost([FromBody] InitiatePostViewModel parameters) { try { #region Parameters validation // Parameters haven't been initialized. if (parameters == null) { // Initiate the parameter. parameters = new InitiatePostViewModel(); Validate(parameters); } //Request parameters are invalid if (!ModelState.IsValid) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState)); } #endregion #region Account identity search // Search account from request. var account = _identityService.FindAccount(Request.Properties); if (account == null) { throw new Exception("No account has attached to request"); } #endregion #region Category search // Search condition build. var findCategoryConditions = new SearchCategoryViewModel(); findCategoryConditions.Id = parameters.CategoryIndex; // Search the first match category in the database. var categories = _unitOfWork.RepositoryCategories.Search(); var category = await _unitOfWork.RepositoryCategories.Search(categories, findCategoryConditions) .FirstOrDefaultAsync(); if (category == null) { _log.Error($"No category (Id: {parameters.CategoryIndex}) is found in database."); return(Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.CategoryNotFound)); } #endregion #region Post initialization // Initiate new post. var post = new Post(); post.OwnerIndex = account.Id; post.CategoryIndex = parameters.CategoryIndex; post.Title = parameters.Title; post.Body = parameters.Body; post.Created = _timeService.DateTimeUtcToUnix(DateTime.UtcNow); //Add category record _unitOfWork.RepositoryPosts.Insert(post); // Save changes into database. await _unitOfWork.CommitAsync(); #endregion return(Request.CreateResponse(HttpStatusCode.Created, post)); } catch (Exception exception) { _log.Error(exception.Message, exception); return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } }
public async Task <HttpResponseMessage> Login([FromBody] LoginViewModel parameters) { try { // Parameters haven't been initialized. if (parameters == null) { parameters = new LoginViewModel(); Validate(parameters); } // Parameters are invalid. if (!ModelState.IsValid) { return(Request.CreateResponse(HttpStatusCode.BadRequest, FindValidationMessage(ModelState, nameof(parameters)))); } // Search encrypted password. var encryptedPassword = _encryptionService.Md5Hash(parameters.Password); // Search account information from database. // Password submitted to server is already hashed. var account = await UnitOfWork.RepositoryAccounts.Search().Where( x => x.Email.Equals(parameters.Email) && x.Password.Equals(encryptedPassword, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefaultAsync(); // Account is not found. if (account == null) { _log.Info( $"Account [Email : {parameters.Email}] [Password: {parameters.Password}] is not found in database"); return(Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.AccountNotFound)); } // Account is pending. if (account.Status == Statuses.Pending) { _log.Info($"Account [Email: {parameters.Email}] is waiting for approval"); return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, HttpMessages.AccountIsPending)); } // Account is disabled. if (account.Status == Statuses.Disabled) { _log.Info($"Account [Email: {parameters.Email}] is disabled"); return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, HttpMessages.AccountIsPending)); } // Calculate token expiration time. var tokenExpirationTime = DateTime.UtcNow.AddSeconds(_bearerAuthenticationProvider.Duration); var unixTokenExpirationTime = _timeService.DateTimeUtcToUnix(tokenExpirationTime); // Claim identity initialization. var claimsIdentity = new Dictionary <string, object>(); claimsIdentity.Add(ClaimTypes.Email, account.Email); claimsIdentity.Add(ClaimTypes.Hash, account.Password); claimsIdentity.Add(ClaimTypes.Name, account.Nickname); claimsIdentity.Add(ClaimTypes.Expiration, unixTokenExpirationTime.ToString("N")); // Initiate token response. var jwtResponse = new JwtResponse(); jwtResponse.Expire = unixTokenExpirationTime; jwtResponse.Type = "Bearer"; jwtResponse.Token = JsonWebToken.Encode(claimsIdentity, _bearerAuthenticationProvider.Key, JwtHashAlgorithm.HS256); // Search account by using return(Request.CreateResponse(HttpStatusCode.OK, jwtResponse)); } catch (Exception exception) { _log.Error(exception.Message, exception); return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } }
public async Task <HttpResponseMessage> InitiateCategory([FromBody] InitiateCategoryViewModel parameters) { try { #region Parameters validation // Parameters haven't been initialized. if (parameters == null) { parameters = new InitiateCategoryViewModel(); Validate(parameters); } //Request parameters are invalid if (!ModelState.IsValid) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState)); } #endregion #region Account validate // Search account information attached in the current request. var account = _identityService.FindAccount(Request.Properties); if (account == null) { throw new Exception("No account information is attached into current request."); } #endregion #region Record duplicate check var findCategoryConditions = new SearchCategoryViewModel(); findCategoryConditions.Name = new TextSearch(); findCategoryConditions.Name.Value = parameters.Name; findCategoryConditions.Name.Mode = TextComparision.EqualIgnoreCase; // Category has been created before. var categories = UnitOfWork.RepositoryCategories.Search(); var category = await UnitOfWork.RepositoryCategories.Search(categories, findCategoryConditions).FirstOrDefaultAsync(); if (category != null) { _log.Error($"Category with name : {parameters.Name} has been created before."); return(Request.CreateErrorResponse(HttpStatusCode.Conflict, HttpMessages.CategoryDuplicated)); } #endregion #region Record initialization // Search current time on system. var systemTime = _timeService.DateTimeUtcToUnix(DateTime.UtcNow); // Search the id of requester. //Initiate new category category = new Category(); category.CreatorIndex = account.Id; category.Created = systemTime; category.Name = parameters.Name; //Add category record UnitOfWork.RepositoryCategories.Insert(category); // Save changes. await UnitOfWork.CommitAsync(); #endregion return(Request.CreateResponse(HttpStatusCode.Created, category)); } catch (Exception exception) { _log.Error(exception.Message, exception); return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } }