Пример #1
0
 // POST tables/User
 public IHttpActionResult PostUser(RegisterRequest request)
 {
     try
     {
         string errorMessage = ValidationUtilities.ValidateUserDetails(request);
         var    domainObj    = DbUtilities.GetDomainDetails(request.Email);
         if (errorMessage.Equals(string.Empty))
         {
             string otpCode   = AuthorizationUtilities.GenerateOTPCode();
             string userEmail = HttpUtilities.GetUserNameFromToken(this.Request);
             DbUtilities.SaveTheUser(request, otpCode, domainObj, userEmail, request.IsActiveUser);
             AuthorizationUtilities.SendOTPtoUser(request.Email, otpCode);
             return(Ok(HttpUtilities.CustomResp(ErrorCodes.USER_CREATED.ToString())));
         }
         else
         {
             return(BadRequest(errorMessage));
         }
     }
     catch (Exception ex)
     {
         LGSELogger.Error(ex);
         return(InternalServerError(ex));
     }
     //return CreatedAtRoute("Tables", new { id = current.Id }, current);
 }
Пример #2
0
        public IHttpActionResult ResetPassword(SendActivationReq req)
        {
            try
            {
                string currentUsrEmail = HttpUtilities.GetUserNameFromToken(this.Request);
                byte[] salt            = AuthorizationUtilities.generateSalt();
                User   user            = _context.Users.FirstOrDefault(i => i.Id == req.UserId);
                //  if (user.IsActiveUser == false)
                ValidationUtilities.ValidateUserforNewPassword(req.UserId, user);

                string generatedPassword = AuthorizationUtilities.GeneratePassword();
                AuthorizationUtilities.SendPasswordtoUser(user.Email, generatedPassword);
                byte[] pwdhash = AuthorizationUtilities.hash(generatedPassword, user.Salt);
                //  user.Salt = salt;
                user.Password   = pwdhash;//AuthorizationUtilities.hash(generatedPassword, salt);
                user.ModifiedBy = currentUsrEmail;
                // user.UpdatedAt = DateTimeOffset.UtcNow;
                _context.Entry(user).State = System.Data.Entity.EntityState.Modified;
                _context.SaveChanges();
                return(Ok());
            }
            catch (HttpResponseException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                LGSELogger.Error(ex);
                return(InternalServerError(ex));
            }
        }
Пример #3
0
 public IHttpActionResult SendActivationLink(SendActivationReq req)
 {
     try
     {
         string currentUsrEmail = HttpUtilities.GetUserNameFromToken(this.Request);
         var    user            = _context.Users.FirstOrDefault(i => i.Id == req.UserId);
         if (user.IsActiveUser == false)
         {
             return(BadRequest(ErrorCodes.USER_DEACTIVATED_BY_ADMIN.ToString()));
         }
         else if (user.Domain.IsActive == false)
         {
             return(BadRequest(ErrorCodes.DOMAIN_IS_INACTIVE.ToString()));
         }
         ValidationUtilities.ValidateUserforActivationLink(req.UserId, user);
         string otpCode = AuthorizationUtilities.GenerateOTPCode();
         AuthorizationUtilities.SendOTPtoUser(user.Email, otpCode);
         user.OTPCode        = otpCode;
         user.OTPGeneratedAt = DateTimeOffset.UtcNow;
         user.ModifiedBy     = currentUsrEmail;
         // user.UpdatedAt = DateTimeOffset.UtcNow;
         _context.Entry(user).State = System.Data.Entity.EntityState.Modified;
         _context.SaveChanges();
         return(Ok());
     }
     catch (HttpResponseException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         LGSELogger.Error(ex);
         return(InternalServerError(ex));
     }
 }
Пример #4
0
 public IHttpActionResult OTP(BaseRequest request)
 {
     try
     {
         if (!request.Email.Equals(string.Empty))
         {
             //Check the user exists with that Email
             User user = _context.Users.SingleOrDefault(a => a.Email == request.Email);
             //&& a.IsActiveUser == true && a.IsActivated == true && a.Domain.IsActive == true
             if (user != null && user.IsActiveUser == false)
             {
                 return(BadRequest(ErrorCodes.USER_DEACTIVATED_BY_ADMIN.ToString()));//BadRequest(Constants.INVALID_USER);
             }
             else if (user != null && user.IsActivated == false)
             {
                 return(BadRequest(ErrorCodes.USER_NOT_ACVTD.ToString()));//BadRequest(Constants.INVALID_USER);
             }
             else if (user != null && user.Domain.IsActive == false)
             {
                 return(BadRequest(ErrorCodes.DOMAIN_IS_INACTIVE.ToString()));//BadRequest(Constants.INVALID_USER);
             }
             else if (user != null)
             {
                 if (DateTimeOffset.UtcNow < user.OTPGeneratedAt.Value.AddMinutes(Convert.ToInt64(ConfigurationManager.AppSettings[Constants.OTP_REQTIME_CONN_STRING])))
                 {
                     return(BadRequest(ErrorCodes.OTP_GENERATED_ALREADY.ToString())); //HttpUtilities.FrameHTTPResp(HttpStatusCode.OK, Constants.OTP_GENERATED_ALREADY);//Ok(Constants.OTP_GENERATED_ALREADY);
                 }
                 else
                 {
                     string otpCode = AuthorizationUtilities.GenerateOTPCode();
                     user.OTPGeneratedAt = DateTimeOffset.UtcNow;
                     AuthorizationUtilities.SendOTPForPwdReset(user.Email, otpCode);
                     user.OTPCode    = otpCode;
                     user.ModifiedBy = request.Email;
                     //    user.UpdatedAt = DateTimeOffset.UtcNow;
                     _context.SaveChanges();
                     return(Ok(HttpUtilities.CustomResp(ErrorCodes.OTP_GENERATED.ToString())));
                 }
             }
             //user doesn't exists
             return(BadRequest(ErrorCodes.INVALID_USER.ToString()));//BadRequest(Constants.INVALID_USER);
         }
         else
         {
             //Empty Email ID
             return(BadRequest(ErrorCodes.EMPTY_USER_ID.ToString()));//HttpUtilities.FrameHTTPResp(HttpStatusCode.BadRequest, Constants.EMPTY_USER_ID);//BadRequest(Constants.EMPTY_USER_ID);
         }
     }
     catch (Exception ex)
     {
         LGSELogger.Error(ex);
         return(InternalServerError(ex));//HttpUtilities.FrameHTTPResp(HttpStatusCode.BadRequest,ex.Message);   //InternalServerError(ex);
     }
 }
Пример #5
0
        /// <summary>
        /// Compare user entered password with the password saved in Db
        /// </summary>
        /// <param name="oldPassword"></param>
        /// <returns>
        ///     true:  if passwords are same
        ///     false: if password are not same
        /// </returns>
        private bool IsPasswordCorrect(string oldPassword, User account = null)
        {
            if (account == null)
            {
                account = GetLoggedInUser();
            }
            byte[] exisingPassword   = account.Password;
            byte[] oldPasswordSalted = AuthorizationUtilities.hash(oldPassword, account.Salt);

            //compare old password
            return(Utilities.Utilities.slowEquals(oldPasswordSalted, exisingPassword));
        }
        /// <summary>
        /// Generates a token for Partner tenant using partner user refresh token
        /// The expiry time calculation explined below is not strong.
        /// please use stardard ADAL library to gain access token by refresh token, which provides strongly typed classes with proper expirty time calculation.
        /// </summary>
        /// <param name="partnerTenantId">partner tenant id</param>
        /// <returns>
        /// Access token and expiry time.
        /// </returns>
        public static async Task <Tuple <string, DateTimeOffset> > LoginToGraph(string partnerTenantId)
        {
            KeyVaultProvider provider     = new KeyVaultProvider();
            string           refreshToken = await provider.GetSecretAsync(partnerTenantId);

            Newtonsoft.Json.Linq.JObject token = await AuthorizationUtilities.GetAADTokenFromRefreshToken(
                "https://login.microsoftonline.com/" + partnerTenantId,
                "https://graph.microsoft.com",
                CSPApplicationId,
                CSPApplicationSecret,
                refreshToken);

            return(new Tuple <string, DateTimeOffset>(token["access_token"].ToString(), DateTimeOffset.UtcNow + TimeSpan.FromTicks(long.Parse(token["expires_on"].ToString()))));
        }
        /// <summary>
        /// Generates a token for Customer tenant using partner user refresh token
        /// The expiry time calculation explined below is not strong.
        /// please use stardard ADAL library to gain access token by refresh token, which provides strongly typed classes with proper expirty time calculation.
        /// </summary>
        /// <param name="partnerTenantId">partner tenant id</param>
        /// <param name="customerTenantId">customer tenant id</param>
        /// <returns>
        /// Access token and expiry time.
        /// </returns>
        public static async Task <Tuple <string, DateTimeOffset> > LoginToCustomerGraph(string partnerTenantId, string customerTenantId)
        {
            KeyVaultProvider provider     = new KeyVaultProvider();
            string           refreshToken = await provider.GetSecretAsync(partnerTenantId);

            JObject token = await AuthorizationUtilities.GetAADTokenFromRefreshToken(
                $"{AADInstance}/{customerTenantId}",
                "https://graph.windows.net",
                CPVApplicationId,
                CPVApplicationSecret,
                refreshToken);

            return(new Tuple <string, DateTimeOffset>(token["access_token"].ToString(), DateTimeOffset.UtcNow + TimeSpan.FromTicks(long.Parse(token["expires_on"].ToString()))));
        }
        public static async Task <Tuple <string, DateTimeOffset> > LoginToPartnerCenter(string tenantId)
        {
            KeyVaultProvider provider     = new KeyVaultProvider();
            string           refreshToken = await provider.GetSecretAsync(tenantId);

            JObject token = await AuthorizationUtilities.GetAADTokenFromRefreshToken(
                $"{AADInstance}/{tenantId}",
                "https://api.partnercenter.microsoft.com",
                CPVApplicationId,
                CPVApplicationSecret,
                refreshToken);

            return(new Tuple <string, DateTimeOffset>(token["access_token"].ToString(), DateTimeOffset.UtcNow + TimeSpan.FromTicks(long.Parse(token["expires_on"].ToString()))));
        }
Пример #9
0
        public IHttpActionResult ForgotPassword(ActivationRequest request)
        {
            try
            {
                var user = DbUtilities.GetUserByEmail(request.Email);
                if (user != null)
                {
                    string validStatus = ValidationUtilities.ValidateForActivation(request, user, true);
                    if (validStatus == Constants.SUCCESS_MSG)
                    {
                        User account = _context.Users.Where(a => a.Email == request.Email).SingleOrDefault();
                        //if (IsPasswordCorrect(request.Password, account))
                        //    return BadRequest(ErrorCodes.PASSWORD_ALREADY_USED.ToString());
                        byte[] pwdhash = AuthorizationUtilities.hash(request.Password, account.Salt);

                        //  account.UpdatedAt = DateTime.UtcNow;
                        account.ModifiedBy  = request.Email;
                        account.IsActivated = true;
                        account.OTPCode     = "";

                        //add the new password to the database
                        account.Password     = pwdhash;
                        account.PwdStartDate = DateTimeOffset.UtcNow;
                        account.IsLocked     = false;
                        _context.SaveChanges();
                        return(Ok(HttpUtilities.CustomResp(ErrorCodes.PWD_UPDATED.ToString())));
                    }
                    else
                    {
                        return(BadRequest(validStatus));
                    }
                }
                else
                {
                    //user doesn't exists
                    return(BadRequest(ErrorCodes.INVALID_USER.ToString()));
                }
            }
            catch (Exception ex)
            {
                LGSELogger.Error(ex);
                return(InternalServerError(ex));
            }
        }
Пример #10
0
 public IHttpActionResult ChangePassword(ChangePasswordRequest request)
 {
     try
     {
         //get user details from request _context
         User account = GetLoggedInUser();
         if (account != null)
         {
             //compare old password with the one saved in Db
             if (IsPasswordCorrect(request.OldPassword))
             {
                 if (IsPasswordCorrect(request.NewPassword))
                 {
                     return(BadRequest(ErrorCodes.PASSWORD_ALREADY_USED.ToString()));
                 }
                 byte[] pwdhash = AuthorizationUtilities.hash(request.NewPassword, account.Salt);
                 //     account.UpdatedAt = DateTime.UtcNow;
                 account.ModifiedBy   = account.Email;
                 account.Password     = pwdhash;
                 account.PwdStartDate = DateTimeOffset.UtcNow;
                 // _context.Entry(account).State = System.Data.Entity.EntityState.Modified;
                 _context.SaveChanges();
                 return(Ok(HttpUtilities.CustomResp(ErrorCodes.PWD_CHANGED.ToString())));
             }
             else
             {
                 return(BadRequest(ErrorCodes.OLD_PWD_NOTMATCHED.ToString()));
             }
         }
         else
         {
             return(BadRequest(ErrorCodes.INVALID_USER.ToString()));
         }
         //return Ok();
     }
     catch (Exception ex)
     {
         //Services.Log.Error(ex);
         LGSELogger.Error(ex);
         return(InternalServerError(ex));
     }
 }
        /// <summary>
        /// Recieve the AuthCode and exchange it for an access token and refresh token
        /// </summary>
        /// <param name="notificationMessage"></param>
        private static async Task HandleAuthorizationCodeReceivedNotification(AuthorizationCodeReceivedNotification notificationMessage)
        {
            string partnerTenantId = notificationMessage.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            // Acquire a token using AuthCode
            Newtonsoft.Json.Linq.JObject tokenResult = await AuthorizationUtilities.GetAADTokenFromAuthCode(
                $"{AadInstance}/{partnerTenantId}",
                "https://api.partnercenter.microsoft.com",
                CSPApplicationId,
                CSPApplicationSecret,
                notificationMessage.Code,
                notificationMessage.OwinContext.Request.Uri.ToString());

            string refreshToken = tokenResult["refresh_token"].ToString();

            // Store the refresh token using partner tenant id as the key.
            // Marketplace application will use the partner tenant id as a key to retrive the refresh token to get authenticated against the user.
            KeyVaultProvider provider = new KeyVaultProvider();

            await provider.AddSecretAsync(partnerTenantId, refreshToken).ConfigureAwait(false);
        }
Пример #12
0
        public IHttpActionResult ActivateUser(ActivationRequest request)
        {
            try
            {
                var dbUser = DbUtilities.GetUserByEmail(request.Email);
                if (dbUser != null)
                {
                    string validStatus = DbUtilities.ValidateForActivation(request, dbUser, false);
                    if (validStatus == Constants.SUCCESS_MSG)
                    {
                        //Need to get Oorg id based on domain
                        byte[] salt = AuthorizationUtilities.generateSalt();

                        User account = _context.Users.SingleOrDefault(a => a.Email == request.Email);
                        //    account.UpdatedAt = DateTime.UtcNow;
                        account.ModifiedBy  = request.Email;
                        account.Salt        = salt;
                        account.Password    = AuthorizationUtilities.hash(request.Password, salt);
                        account.IsActivated = true;
                        account.OTPCode     = "";
                        _context.SaveChanges();
                        return(Ok(HttpUtilities.CustomResp(ErrorCodes.USER_ACTIVATED.ToString())));
                    }
                    else
                    {
                        return(BadRequest(validStatus));
                    }
                }
                else
                {
                    return(BadRequest(ErrorCodes.INVALID_USER.ToString()));
                }
            }
            catch (Exception ex)
            {
                LGSELogger.Error(ex);
                return(InternalServerError(ex));
            }
        }
Пример #13
0
 public IHttpActionResult SignUp(RegisterRequest request)
 {
     try
     {
         string errorMessage = ValidationUtilities.ValidateUserDetails(request);
         var    domainObj    = DbUtilities.GetDomainDetails(request.Email);
         if (errorMessage.Equals(string.Empty))
         {
             string otpCode = AuthorizationUtilities.GenerateOTPCode();
             DbUtilities.SaveTheUser(request, otpCode, domainObj, request.Email, true);
             AuthorizationUtilities.SendOTPtoUser(request.Email, otpCode);
             return(Ok(HttpUtilities.CustomResp(ErrorCodes.USER_REGISTERED.ToString())));
         }
         else
         {
             return(BadRequest(errorMessage));
         }
     }
     catch (Exception ex)
     {
         LGSELogger.Error(ex);
         return(InternalServerError(ex));
     }
 }
Пример #14
0
 public IHttpActionResult Login(LoginRequest request)
 {
     try
     {
         User account = _context.Users.Where(a => a.Email == request.Email).SingleOrDefault();
         ValidationUtilities.ValidateUserForLogin(request, account);
         if (account != null)
         {
             if (account.IsActiveUser == false)
             {
                 return(BadRequest(ErrorCodes.USER_DEACTIVATED_BY_ADMIN.ToString()));
                 //var response = HttpUtilities.FrameHTTPResp(System.Net.HttpStatusCode.BadRequest, ErrorCodes.USER_DEACTIVATED_BY_ADMIN);
                 // throw new HttpResponseException(response);
             }
             if (account.IsActivated == false)
             {
                 return(BadRequest(ErrorCodes.USER_NOT_ACVTD.ToString()));
             }
             if (!account.IsLocked)
             {
                 byte[] incoming = AuthorizationUtilities.hash(request.Password, account.Salt);
                 if (Utilities.Utilities.slowEquals(incoming, account.Password))
                 {
                     if (account.IsActivated)
                     {
                         //Audit Trial Entry.
                         //DbUtilities.AuditTrialEntry(account, AuditTrialStatus.SUCCESS, AuditTrialOpType.LOGIN, this.Request);
                         //Creating a Token
                         ClaimsIdentity claimsIdentity = new ClaimsIdentity();
                         claimsIdentity.AddClaim(new Claim(Constants.STR_FIRSTNAME, account.FirstName));
                         claimsIdentity.AddClaim(new Claim(Constants.STR_LASTNAME, account.LastName));
                         claimsIdentity.AddClaim(new Claim(ClaimTypes.Email, request.Email));
                         claimsIdentity.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, request.Email));
                         claimsIdentity.AddClaim(new Claim("UserId", account.Id));
                         List <Role> roles = (from userMaps in _context.UserRoleMaps.ToList()
                                              join rol in _context.Roles.ToList() on userMaps.RoleId equals rol.Id
                                              where userMaps.UserId == account.Id && userMaps.Deleted == false
                                              select rol).ToList();
                         if (roles != null && roles.Count > 0)
                         {
                             foreach (var item in roles)
                             {
                                 claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, item.RoleName));
                                 //claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, item.RoleName + "|" + item.Id));
                             }
                         }
                         // Update user details:
                         UpdateUserDetailsInLogin(account);
                         JwtSecurityToken token = AuthorizationUtilities.GetAuthenticationTokenForUser(request.Email, claimsIdentity.Claims.ToArray());
                         return(Ok(new
                         {
                             Token = token.RawData,
                             Username = request.Email,
                             UserId = account.Id
                         }));
                     }
                     else
                     {
                         return(BadRequest(ErrorCodes.USER_NOT_ACVTD.ToString()));
                     }
                 }
                 else
                 {
                     //Audit Trial Entry.
                     DbUtilities.AuditTrialEntry(account, AuditTrialStatus.FAILURE, AuditTrialOpType.LOGIN, this.Request);
                     // return Unauthorized();
                     return(BadRequest(ErrorCodes.PASSWORD_NOTMATCHED.ToString()));
                 }
             }
             else
             {
                 return(BadRequest(ErrorCodes.ACCOUNT_LOCKED.ToString()));
             }
         }
         return(Unauthorized());
     }
     catch (HttpResponseException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         LGSELogger.Error(ex);
         return(InternalServerError(ex));
     }
 }