Beispiel #1
0
        //POST : /api/ApplicationUser/Login
        public async Task <IActionResult> Login(LoginModel model)
        {
            var user = await _userManager.FindByNameAsync(model.UserName);

            if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
            {
                try
                {
                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject            = new ClaimsIdentity(new Claim[] { new Claim("UserID", user.Id.ToString()) }),
                        Expires            = DateTime.UtcNow.AddDays(1),
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.JWT_Secret)), SecurityAlgorithms.HmacSha256Signature)
                    };
                    var tokenHandler  = new JwtSecurityTokenHandler();
                    var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                    var access_token  = tokenHandler.WriteToken(securityToken);

                    UserAudit userAudit = new UserAudit
                    {
                        userId     = user.Id,
                        ActionDate = DateTimeOffset.UtcNow,
                        ActionName = "Login",
                        Status     = "Success"
                    };
                    _authenticationContext.Add(userAudit);
                    _authenticationContext.SaveChanges();

                    return(Ok(new { access_token }));
                }
                catch (Exception)
                {
                    UserAudit userAudit = new UserAudit
                    {
                        userId     = user.Id,
                        ActionDate = DateTimeOffset.UtcNow,
                        ActionName = "Login",
                        Status     = "Failed - System Error"
                    };
                    _authenticationContext.Add(userAudit);
                    _authenticationContext.SaveChanges();
                    return(BadRequest(new { message = "Funtion System Error." }));;
                }
            }
            else
            {
                UserAudit userAudit = new UserAudit
                {
                    userId     = user.Id,
                    ActionDate = DateTimeOffset.UtcNow,
                    ActionName = "Login",
                    Status     = "Failed - Username or password is incorrect."
                };
                _authenticationContext.Add(userAudit);
                _authenticationContext.SaveChanges();
                return(BadRequest(new { message = "Username or password is incorrect." }));
            }
        }
Beispiel #2
0
        public async Task AddUser(NewUserMessage message)
        {
            var salt = GenerateSalt();
            var hash = HashPassword(message.Password, salt);

            var user = new User
            {
                Id       = message.Id,
                Email    = message.Email,
                Username = message.Username,
                Hash     = hash,
                Salt     = salt,
                Role     = UserRole.User
            };

            _authenticationContext.Add(user);
            await _authenticationContext.SaveChangesAsync();
        }
        public async Task <IActionResult> Register([FromBody] UserDTO credentials)
        {
            var user = new User
            {
                Username = credentials.Username,
                Password = CryptoHelper.Crypto.HashPassword(credentials.Password)
            };

            _context.Add(user);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("Register", null, user.Id));
        }
        public async Task <IActionResult> Create([Bind("id,Name,Age,Gender")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                ViewBag.Gender = new SelectList(new List <string> {
                    "Male", "Female"
                });

                employee.DateOfEmployment = DateTime.Now.ToString("yyyy/MM/dd//HH:mm:ss");
                _context.Add(employee);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(employee));
        }
Beispiel #5
0
 public void Add <T>(T entity) where T : class
 {
     _authContext.Add(entity);
 }
 public void Insert <T>(T entity) where T : class
 {
     _context.Add(entity);
 }
 public void Add <T>(T entity) where T : class
 {
     _logger.LogInformation($"Adding an object of type {entity.GetType()} to the context");
     _context.Add(entity);
     _context.SaveChanges();
 }
        public async Task <IActionResult> UploadAsync()
        {
            try
            {
                ApplicationUser user = await GetActualUserAsync(_userManager);

                var           req = Request;
                var           imageDetailsString   = Request.Form["detailsOfImage"];
                ImageModel    imageModel           = Newtonsoft.Json.JsonConvert.DeserializeObject <ImageModel>(imageDetailsString);
                var           cropPropertiesString = Request.Form["cropproperites"];
                ImageCropProp cropProperties       = Newtonsoft.Json.JsonConvert.DeserializeObject <ImageCropProp>(cropPropertiesString);
                var           typeOfProcessing     = Request.Form["typeOfProcessing"];
                Enum.TryParse(typeOfProcessing, out TypeOfProcessing createdEnum);
                var file = Request.Form.Files[0];
                var partialFolderName = Path.Combine("Resources", "Images");
                var folderName        = Path.Combine(partialFolderName, user.UserName);
                var pathToSave        = Path.Combine(Directory.GetCurrentDirectory(), folderName);
                if (file.Length > 0)
                {
                    var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    var fullPath = Path.Combine(pathToSave, fileName);
                    int count    = 0;
                    while (System.IO.File.Exists(fullPath))
                    {
                        count++;
                        fileName = fileName.Replace(".jpg", $"({count}).jpg");
                        fullPath = Path.Combine(pathToSave, fileName);
                    }
                    var dbPath = Path.Combine(folderName, fileName).Replace("\\", "//");
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }

                    if (imageModel == null)
                    {
                        return(BadRequest("Obiekt- zdjęcie nie istnieje"));
                    }

                    if (!ModelState.IsValid)
                    {
                        return(BadRequest("Niepoprawny obiekt"));
                    }

                    string processedImgPath = "";

                    if (createdEnum != TypeOfProcessing.Brak)
                    {
                        processedImgPath = this.CreateImageOperation(fileName, user, createdEnum, cropProperties);
                    }

                    string EnumVariableDisplay = "Brak Operacji Przetwarzania";
                    switch (createdEnum)
                    {
                    case TypeOfProcessing.Progowanie:
                        EnumVariableDisplay = "Progowanie";
                        break;

                    case TypeOfProcessing.KSrednich:
                        EnumVariableDisplay = "Metoda k-średnich";
                        break;

                    case TypeOfProcessing.RedukcjaPoziomowSzarosci:
                        EnumVariableDisplay = "Redukcja Poziomów Szarości";
                        break;

                    default:
                        EnumVariableDisplay = "Brak Operacji Przetwarzania";
                        break;
                    }

                    var image = new Image();
                    image.ImageID           = Guid.NewGuid();
                    image.Description       = imageModel.Description;
                    image.ImgPath           = imageModel.ImgPath;
                    image.Length            = imageModel.Length;
                    image.Width             = imageModel.Width;
                    image.Name              = imageModel.Name;
                    image.ImgPath           = dbPath;
                    image.ProcessedImgPath  = processedImgPath;
                    image.TypeOfProcessing  = EnumVariableDisplay;
                    image.ApplicationUserID = user.Id;
                    _contex.Add(image);
                    _contex.SaveChanges();
                    return(StatusCode(201));
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(500, $"Internal server error: {ex}"));
            }
        }