Ejemplo n.º 1
0
        public HttpResponseMessage Registration(UserModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState));
            }
            else
            {
                var encryptedPassword = EncryptDecryptPassword.EncryptPlainTextToCipherText(model.Password);

                db.UserTbls.Add(new UserTbl()
                {
                    CityId         = model.CityId,
                    FirstName      = model.FirstName,
                    LastName       = model.LastName,
                    Email          = model.Email,
                    MobileNumber   = model.MobileNumber,
                    FlatNumber     = model.FlatNumber,
                    CountryId      = model.CountryId,
                    StateId        = model.StateId,
                    SocityName     = model.SocityName,
                    DateModified   = DateTime.Now,
                    DateAdded      = DateTime.Now,
                    WhatsAppNumber = model.WhatsAppNumber,
                    WingName       = model.WingName,
                    Landmark       = model.Landmark,
                    Password       = encryptedPassword,
                    UserName       = model.UserName,
                    Token          = model.Token
                });
                db.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK));
            }
        }
Ejemplo n.º 2
0
 public HttpResponseMessage Login(UserTbl model)
 {
     if (ModelState.IsValid)
     {
         var encryptedPasswordString = EncryptDecryptPassword.EncryptPlainTextToCipherText(model.Password);
         var user = db.UserTbls.FirstOrDefault(item => item.UserName == model.UserName && item.Password == encryptedPasswordString);
         if (user != null)
         {
             user.Token = Guid.NewGuid();
             db.SaveChanges();
             return(Request.CreateResponse(HttpStatusCode.OK, new
             {
                 Token = user.Token,
                 Name = string.Concat(user.FirstName, " ", user.LastName)
             }));
         }
         else
         {
             return(Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Username and password"));
         }
     }
     else
     {
         return(Request.CreateResponse(HttpStatusCode.BadRequest, ModelState));
     }
 }
Ejemplo n.º 3
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool   validKey = false;
            string apiKey   = EncryptDecryptPassword.EncryptPlainTextToCipherText(Convert.ToString(ConfigurationSettings.AppSettings["ApiKey"]));
            IEnumerable <string> requestHeaders;
            var checkApiKeyExists = request.Headers.TryGetValues("ApiKey", out requestHeaders);

            if (checkApiKeyExists)
            {
                if (requestHeaders.FirstOrDefault().Equals(apiKey))
                {
                    validKey = true;
                }
            }
            if (!validKey)
            {
                return(new HttpResponseMessage(HttpStatusCode.Forbidden)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new { message = "Invalid API Key" })),
                    ReasonPhrase = "Invalid API Key"
                });
            }
            var response = await base.SendAsync(request, cancellationToken);

            return(response);
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Post(RegistrationModel model)
        {
            try
            {
                var user = await this.context.RegisterUsers.FirstOrDefaultAsync(a => a.UserName == model.UserName);

                if (user == null)
                {
                    model.UserId   = Guid.NewGuid().ToString();
                    model.UserType = 0;
                    model.Password = EncryptDecryptPassword.Encrypt(model.Password, model.UserId.ToString());
                    this.context.RegisterUsers.Add(model);
                    await this.context.SaveChangesAsync();

                    return(Ok(model));
                }
                else
                {
                    return(BadRequest("This User is already registered with us!!!"));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        /// <summary>
        /// Encrypt Answer
        /// </summary>
        /// <param name="answer"></param>
        /// <returns></returns>
        // FIXED-FEB16 - Move "[^0-9a-z]+" to constant
        public string EncryptAnswer(string answer)
        {
            string encryptedString = string.Empty;

            if (answer != null)
            {
                string convertToLower = answer.ToLower();
                encryptedString = Regex.Replace(convertToLower, Constants.SpecialCharacterPatterne, string.Empty);
            }
            return(EncryptDecryptPassword.EncryptText(encryptedString));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Validates the user.
        /// </summary>
        /// <param name="password"></param>
        /// <param name="userDetails"></param>
        /// <returns></returns>
        private bool ValidateUser(string password, User userDetails)
        {
            if (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(userDetails.PasswordHash) &&
                !string.IsNullOrEmpty(userDetails.PasswordSalt))
            {
                string passwordInput = string.Format("{0}{1}", password, userDetails.PasswordSalt);

                string passwordStored = EncryptDecryptPassword.DecryptText(userDetails.PasswordHash);
                userDetails.ValidLogin = String.CompareOrdinal(passwordInput, passwordStored) == 0;
            }
            if (userDetails.UserTypeId != 1) //not SSI Admin
            {
                PostApiResponse <bool>(Constants.User, Constants.UpdateUserLogin, userDetails, true);
            }
            return(userDetails.ValidLogin);
        }
 /// <summary>
 /// Add question answer and password.
 /// </summary>
 /// <returns></returns>
 public int AddQuestionAnswerAndPassword(User user)
 {
     if (user != null)
     {
         string passwordSalt = GetPasswordSalt(user);
         string passwordHash = EncryptDecryptPassword.EncryptText(string.Format("{0}{1}", user.PasswordHash, passwordSalt));
         _cmd = _db.GetStoredProcCommand("AddQuestionAnswerAndPassword");
         _db.AddInParameter(_cmd, "@UserID", DbType.Int32, user.UserId);
         _db.AddInParameter(_cmd, "@PasswordHash", DbType.String, passwordHash);
         _db.AddInParameter(_cmd, "@PasswordSalt", DbType.String, passwordSalt);
         _db.AddInParameter(_cmd, "@SecuirtyQuestionAnswer", DbType.Xml, Serializer.ToXml(user.UserSecurityQuestion));
         _db.AddInParameter(_cmd, "@EmailType", DbType.Int32, user.EmailType);
         _db.AddInParameter(_cmd, "@UserName", DbType.String, user.RequestedUserName);
         return(Convert.ToInt32(_db.ExecuteScalar(_cmd)));
     }
     return(0);
 }
        /// <summary>
        /// Add question answer and password.
        /// </summary>
        /// <returns></returns>
        private string GetPasswordSalt(User user)
        {
            string passwordSalt;

            if (user.EmailType == Convert.ToInt32(Enums.EmailType.AccountActivation) || user.EmailType == Convert.ToInt32(Enums.EmailType.AccountReset))
            {
                passwordSalt = EncryptDecryptPassword.GenerateSalt();
            }
            else
            {
                _cmd = _db.GetStoredProcCommand("GetPasswordSalt");
                _db.AddInParameter(_cmd, "@UserID", DbType.Int32, user.UserId);

                passwordSalt = Convert.ToString(_db.ExecuteScalar(_cmd));
            }
            return(passwordSalt);
        }
        /// <summary>
        /// View AccountActivation Page
        /// </summary>
        public ActionResult AccountActivation(string token)
        {
            string guid = EncryptDecryptPassword.DecryptText(token);

            if (!string.IsNullOrEmpty(guid))
            {
                UserViewModel userViewModel = new UserViewModel {
                    UserGuid = new Guid(guid)
                };
                User user     = Mapper.Map <UserViewModel, User>(userViewModel);
                User userinfo = PostApiResponse <User>(Constants.User, Constants.ValidateToken, user, true);
                if (userinfo != null)
                {
                    userViewModel = Mapper.Map <User, UserViewModel>(userinfo);
                    return(View(userViewModel));
                }
            }
            return(View(new UserViewModel()));
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Login(LoginModel model)
        {
            try
            {
                var user = await this.context.RegisterUsers.FirstOrDefaultAsync(a => a.UserName == model.UserName);

                if (user != null)
                {
                    var testing  = EncryptDecryptPassword.Encrypt(model.Password, user.UserId);
                    var password = EncryptDecryptPassword.Decrypt(user.Password, user.UserId);
                    if (password == model.Password)
                    {
                        var tokenDescriptor = new SecurityTokenDescriptor
                        {
                            Subject = new ClaimsIdentity(new Claim[]
                            {
                                new Claim("UserID", user.UserId.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 SecurityToken = tokenHandler.WriteToken(securityToken);
                        return(Ok(new { SecurityToken, user }));
                    }
                    else
                    {
                        return(BadRequest("Password is incorrect"));
                    }
                }
                else
                {
                    return(BadRequest("Username is incorrect."));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest("Incorrect username or password"));
            }
        }
Ejemplo n.º 11
0
        public JsonResult Attempt(string username, string password)
        {
            try
            {
                //check if model is valid
                if (ModelState.IsValid)
                {
                    //get the result of login using ignition web service
                    string result = HttpHandler.UserLogin(username, password);

                    //handle error
                    if (result == null || result == "")
                    {
                        response.Add("success", false);
                        response.Add("error", true);
                        response.Add("message", "Something went wrong. Please try again later.");
                    }
                    else
                    {
                        if (Convert.ToBoolean(result) == true)
                        {
                            //if the result is true get the user info from AD web service

                            string userType = "";

                            //init the encryptor/decryptor
                            EncryptDecryptPassword e = new EncryptDecryptPassword();

                            //use default credentials for the service
                            HttpClientHandler handler = new HttpClientHandler();
                            handler.UseDefaultCredentials = true;

                            //init the client
                            HttpClient client = new HttpClient(handler);
                            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                            //get the user type from the local db and use it to display the position
                            //we are not using the AD's employee position. instead we will use our application's user type for the position
                            try
                            {
                                userType = UserModels.GetPosition(username);
                            }
                            catch {
                                userType = "N/A";
                            }

                            bool isLoginSuperVision = UserModels.isLoginSuperVision(username);

                            JavaScriptSerializer j = new JavaScriptSerializer();

                            //init the url for the service
                            var url = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["env"].ToString() + "_api_base_url"].ToString() + "login/userinfo?username="******"&json=true";
                            HttpResponseMessage res = client.GetAsync(url).Result;

                            //if success create session and cookie to store login status
                            if (res.IsSuccessStatusCode)
                            {
                                try
                                {
                                    //create the session and cookie based on the result from AD service (user info)
                                    string  strJson = res.Content.ReadAsStringAsync().Result;
                                    dynamic jObj    = (JObject)JsonConvert.DeserializeObject(strJson);
                                    object  a       = j.Deserialize(strJson, typeof(object));
                                    var     dict    = JsonConvert.DeserializeObject <Dictionary <string, object> >(strJson);

                                    HttpContext.Session.Add("Username", username);
                                    HttpContext.Session.Add("Name", dict["cn"]);
                                    HttpContext.Session.Add("Position", userType);
                                    HttpContext.Session.Add("isLoginSuperVision", isLoginSuperVision);
                                    HttpContext.Session.Add("EmployeeNumber", dict["employeeNumber"].ToString());

                                    string thumbnail = "";

                                    try
                                    {
                                        thumbnail = dict["thumbnailPhoto"].ToString();
                                    }
                                    catch { }

                                    if (thumbnail.ToString() == null || thumbnail == "")
                                    {
                                        byte[] imageBytes        = ReadImageFile(Server.MapPath("~/Content/template/images/default_photo.jpg"));
                                        string imageBase64String = Convert.ToBase64String(imageBytes);
                                        string defaultImage      = imageBase64String;
                                        thumbnail = defaultImage;
                                    }

                                    HttpContext.Session.Add("ThumbnailPhoto", thumbnail);

                                    HttpHandler.UpdateThumbnailPhoto(username, thumbnail);

                                    DateTime now = DateTime.Now;

                                    try
                                    {
                                        HttpCookie cookieThumbnailPhoto = new HttpCookie("ThumbnailPhoto");
                                        cookieThumbnailPhoto.Value   = thumbnail;
                                        cookieThumbnailPhoto.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookieThumbnailPhoto);

                                        HttpCookie cookieName = new HttpCookie("Name");
                                        cookieName.Value   = dict["cn"].ToString();
                                        cookieName.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookieName);

                                        HttpCookie cookiePositon = new HttpCookie("Position");
                                        cookiePositon.Value   = userType;
                                        cookiePositon.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookiePositon);

                                        HttpCookie cookieLoginSupervision = new HttpCookie("isLoginSuperVision");
                                        cookieLoginSupervision.Value   = isLoginSuperVision.ToString();
                                        cookieLoginSupervision.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookieLoginSupervision);

                                        HttpCookie cookieEmployeeNumber = new HttpCookie("EmployeeNumber");
                                        cookieEmployeeNumber.Value   = dict["employeeNumber"].ToString();
                                        cookieEmployeeNumber.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookieEmployeeNumber);
                                    }
                                    catch { }
                                }
                                catch
                                {
                                    //handle users not in the AD (standalone user for the application)

                                    //get the default thumbnail photo
                                    byte[] imageBytes        = ReadImageFile(Server.MapPath("~/Content/template/images/default_photo.jpg"));
                                    string imageBase64String = Convert.ToBase64String(imageBytes);

                                    string defaultImage = imageBase64String;

                                    //create session and cookie
                                    HttpContext.Session.Add("Username", username);
                                    HttpContext.Session.Add("Name", username);
                                    HttpContext.Session.Add("Position", userType);
                                    HttpContext.Session.Add("isLoginSuperVision", isLoginSuperVision);
                                    HttpContext.Session.Add("EmployeeNumber", "");
                                    HttpContext.Session.Add("ThumbnailPhoto", defaultImage);

                                    HttpHandler.UpdateThumbnailPhoto(username, defaultImage);

                                    DateTime now = DateTime.Now;

                                    try
                                    {
                                        HttpCookie cookieThumbnailPhoto = new HttpCookie("ThumbnailPhoto");
                                        cookieThumbnailPhoto.Value   = defaultImage;
                                        cookieThumbnailPhoto.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookieThumbnailPhoto);

                                        HttpCookie cookieName = new HttpCookie("Name");
                                        cookieName.Value   = username;
                                        cookieName.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookieName);

                                        HttpCookie cookiePosition = new HttpCookie("Position");
                                        cookiePosition.Value   = userType;
                                        cookiePosition.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookiePosition);

                                        HttpCookie cookieLoginSupervision = new HttpCookie("isLoginSuperVision");
                                        cookieLoginSupervision.Value   = isLoginSuperVision.ToString();
                                        cookieLoginSupervision.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookieLoginSupervision);

                                        HttpCookie cookieEmployeeNumber = new HttpCookie("EmployeeNumber");
                                        cookieEmployeeNumber.Value   = "";
                                        cookieEmployeeNumber.Expires = now.AddDays(30);
                                        Response.Cookies.Add(cookieEmployeeNumber);
                                    }
                                    catch {
                                    }
                                }

                                r.Add("success", true);
                                r.Add("error", false);
                            }

                            var check = r["success"];
                            if (check.ToString() == "True")
                            {
                                response.Add("message", "Login Successful");
                                response.Add("success", true);
                                response.Add("error", false);
                            }
                            else
                            {
                                throw new Exception("Login failed!");
                            }
                        }
                        else
                        {
                            response.Add("success", false);
                            response.Add("error", true);
                            response.Add("message", "Invalid username and/or password.");
                        }
                    }
                }
                else
                {
                    throw new Exception("Login failed!");
                }
            }
            catch (Exception e)
            {
                response.Add("success", false);
                response.Add("error", true);
                response.Add("message", e.ToString());
            }


            //return the json response
            return(Json(response, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// IsEmail Notification Send
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool IsEmailNotificationSend(User user)
        {
            if (user != null)
            {
                string emailContent, emailSubject = string.Empty;
                string serverMapPath = user.EmailType == Convert.ToInt32(Enums.EmailType.AccountActivation)
                    ? Server.MapPath(Constants.MailMessageTemplate)
                    : Server.MapPath(Constants.PasswordResetTemplate);
                using (StreamReader reader = new StreamReader(serverMapPath))
                {
                    emailContent = reader.ReadToEnd();
                }
                switch ((Enums.EmailType)Convert.ToInt32(user.EmailType))
                {
                case Enums.EmailType.AccountActivation:
                    emailSubject = Constants.MailSubject;
                    emailContent = emailContent.Replace("##LINK", Constants.ActivationMailLink);
                    break;

                case Enums.EmailType.AccountReset:
                    emailSubject = Constants.MailSubjectAccountReset;
                    emailContent = emailContent.Replace("##LINK", Constants.ResetAccountMailLink);
                    break;

                case Enums.EmailType.ChangePassword:
                    emailSubject = Constants.MailSubjectChangePassword;
                    emailContent = emailContent.Replace("##LINK", Constants.ChangePasswordMailLink);
                    break;

                case Enums.EmailType.PasswordReset:
                    emailSubject = Constants.MailSubjectPasswordReset;
                    emailContent = emailContent.Replace("##LINK", Constants.ResetPasswordMailLink);
                    break;

                case Enums.EmailType.RecoverPassword:
                    emailSubject = Constants.MailSubjectRecoverPassword;
                    emailContent = emailContent.Replace("##LINK", Constants.RecoverPasswordMailLink);
                    break;
                }

                Uri    url        = System.Web.HttpContext.Current.Request.Url;
                string domainName = string.Format("{0}/{1}", url.GetLeftPart(UriPartial.Authority),
                                                  (url.Segments.Length >= 2) ? url.Segments[1] : String.Empty);

                //email token
                string emailLink = string.Format("{0}{1}{2}", domainName, Constants.EmailUrl,
                                                 Server.UrlEncode(EncryptDecryptPassword.EncryptText(user.UserGuid.ToString())));

                emailContent = emailContent.Replace("##DATA", user.EmailType == Convert.ToInt32(Enums.EmailType.AccountActivation) ?
                                                    Constants.ActivationMailBody : Constants.PasswordMailBody);

                // Change http to https in email link url for production not other environment
                string httpsEmailLink = emailLink;
                if (!Constants.HttpUrls.Contains(url.Host))
                {
                    httpsEmailLink = emailLink.Replace(Constants.Http, Constants.Https);
                }
                emailContent = emailContent.Replace("##GUID", httpsEmailLink);

                if (user.EmailType != Convert.ToInt32(Enums.EmailType.AccountActivation))
                {
                    emailContent = emailContent.Replace("##NAME", string.Format("{0} {1}", user.FirstName, user.LastName));
                }

                try
                {
                    SaveEmailLog(user);
                    Utilities.SendMail(emailSubject, emailContent, user.UserName);
                }
                catch (Exception ex)
                {
                    Log.LogError("Send Email Exeception", user.UserName, ex);
                }
            }
            return(true);
        }