public async Task CreateDefaultAdminUser()
        {
            try
            {
                var adminUser = new ApplicationUserEntities
                {
                    Email                = _adminUserModel.Email,
                    UserName             = _adminUserModel.Username,
                    EmailConfirmed       = true,
                    ProfilePic           = GetDefaultProfilePic(), ///
                    AccountCreatedOn     = DateTime.Now,
                    PhoneNumber          = "1234567890",
                    PhoneNumberConfirmed = true,
                    Firstname            = _adminUserModel.Firstname,
                    Lastname             = _adminUserModel.Lastname,
                    UserRole             = "Administrator",
                    IsActive             = true,
                };


                var result = await _userManager.CreateAsync(adminUser, _adminUserModel.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(adminUser, "Administrator");

                    // Log.Information("Admin User Created {UserName}", adminUser.UserName);
                }
                else
                {
                    var errorString = string.Join(",", result.Errors);
                    Log.Error("Error while creating user {Error}", errorString);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error while creating user {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }
        }
예제 #2
0
        private async Task <ApplicationUserEntities> UpdateProfilePicAsync(IFormCollection formData, ApplicationUserEntities user)
        {
            // First we create an empty array to store old file info
            var oldProfilePic = new string[1];

            // we will store path of old file to delete in an empty array.
            oldProfilePic[0] = Path.Combine(_env.WebRootPath + user.ProfilePic);

            // Create the Profile Image Path
            var profPicPath = _env.WebRootPath + $"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}profile{Path.DirectorySeparatorChar}";

            // If we have received any files for update, then we update the file path after saving to server
            // else we return the user without any changes
            if (formData.Files.Count <= 0)
            {
                return(user);
            }

            var extension   = Path.GetExtension(formData.Files[0].FileName);
            var filename    = DateTime.Now.ToString("yymmssfff");
            var path        = Path.Combine(profPicPath, filename) + extension;
            var dbImagePath = Path.Combine($"{Path.DirectorySeparatorChar}uploads{Path.DirectorySeparatorChar}user{Path.DirectorySeparatorChar}profile{Path.DirectorySeparatorChar}", filename) + extension;

            user.ProfilePic = dbImagePath;

            // Copying New Files to the Server - profile Folder
            await using (var stream = new FileStream(path, FileMode.Create))
            {
                await formData.Files[0].CopyToAsync(stream);
            }

            // Delete old file after successful update
            if (!System.IO.File.Exists(oldProfilePic[0]))
            {
                return(user);
            }

            System.IO.File.SetAttributes(oldProfilePic[0], FileAttributes.Normal);
            System.IO.File.Delete(oldProfilePic[0]);

            return(user);
        }
        private async Task <TokenResponseModel> GenerateNewToken(ApplicationUserEntities user, LoginViewModel model)
        {
            // Create a key to encrypt the JWT
            var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appSettings.Secret));

            // Get user role => check if user is admin
            var roles = await _userManager.GetRolesAsync(user);

            // Creating JWT token
            var tokenHandler = new JwtSecurityTokenHandler();

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.UserName),                      // Sub - Identifies principal that issued the JWT
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),          // Jti - Unique identifier of the token
                    new Claim(ClaimTypes.NameIdentifier, user.Id),                              // Unique Identifier of the user
                    new Claim(ClaimTypes.Role, roles.FirstOrDefault()),                         // Role of the user
                    new Claim("LoggedOn", DateTime.Now.ToString(CultureInfo.InvariantCulture)), // Time When Created
                }),

                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature),
                Issuer             = _appSettings.Site,     // Issuer - Identifies principal that issued the JWT.
                Audience           = _appSettings.Audience, // Audience - Identifies the recipients that the JWT is intended for.
                Expires            = (string.Equals(roles.FirstOrDefault(), "Administrator", StringComparison.CurrentCultureIgnoreCase)) ? DateTime.UtcNow.AddMinutes(60) : DateTime.UtcNow.AddMinutes(Convert.ToDouble(_appSettings.ExpireTime))
            };

            /* Create the unique encryption key for token - 2nd layer protection */
            var encryptionKeyRt  = Guid.NewGuid().ToString();
            var encryptionKeyJwt = Guid.NewGuid().ToString();

            /* Get the Data protection service instance */
            var protectorProvider = _provider.GetService <IDataProtectionProvider>();

            /* Create a protector instance */
            var protectorJwt = protectorProvider.CreateProtector(encryptionKeyJwt);

            /* Generate Token and Protect the user token */
            var token          = tokenHandler.CreateToken(tokenDescriptor);
            var encryptedToken = protectorJwt.Protect(tokenHandler.WriteToken(token));

            /* Create and update the token table */
            TokenEntities newRtoken = new TokenEntities();

            /* Create refresh token instance */
            newRtoken = CreateRefreshToken(_appSettings.ClientId, user.Id, Convert.ToInt32(_appSettings.RtExpireTime));

            /* assign the tne JWT encryption key */
            newRtoken.EncryptionKeyJwt = encryptionKeyJwt;

            newRtoken.EncryptionKeyRt = encryptionKeyRt;

            /* Add Refresh Token with Encryption Key for JWT to DB */
            try
            {
                // First we need to check if the user has already logged in and has tokens in DB
                var rt = _db.Tokens
                         .FirstOrDefault(t => t.UserId == user.Id);

                if (rt != null)
                {
                    // invalidate the old refresh token (by deleting it)
                    _db.Tokens.Remove(rt);

                    // add the new refresh token
                    _db.Tokens.Add(newRtoken);
                }
                else
                {
                    await _db.Tokens.AddAsync(newRtoken);
                }

                // persist changes in the DB
                await _db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }

            // Return Response containing encrypted token
            var protectorRt       = protectorProvider.CreateProtector(encryptionKeyRt);
            var layerOneProtector = protectorProvider.CreateProtector(_dataProtectionKeys.ApplicationUserKey);

            var encAuthToken = new TokenResponseModel
            {
                Token        = layerOneProtector.Protect(encryptedToken),
                Expiration   = token.ValidTo,
                RefreshToken = protectorRt.Protect(newRtoken.Value),
                Role         = roles.FirstOrDefault(),
                Username     = user.UserName,
                UserId       = layerOneProtector.Protect(user.Id),
                ResponseInfo = CreateResponse("Auth Token Created", HttpStatusCode.OK)
            };

            return(encAuthToken);
        }