public IHttpActionResult UpdateCustomerDetails([FromBody] Customer customer)
        {
            bool   isAuthorized     = false;
            bool   isUpdated        = false;
            bool   isCustomerExists = false;
            Action act = () =>
            {
                isAuthorized = GetInternalLoginTokenInternal <Administrator>(out LoginToken <Administrator> loginTokenAdministrator);

                if (isAuthorized)
                {
                    Utility_class_User customerAsUser = _loggedInAdministratorFacade.GetRegisteredUserDetails(customer.USER_ID);
                    isUpdated = _loggedInAdministratorFacade.UpdateCustomerDetails(loginTokenAdministrator, customer, customerAsUser.USER_NAME, customerAsUser.PASSWORD, out isCustomerExists);
                }
            };

            ProcessExceptions(act);
            if (!isAuthorized)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, $"Sorry, but you're not an Administrator. Your accsess is denied.")));
            }

            if (!isCustomerExists)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Sorry, but this Customer doesn't exists in the system")));
            }

            if (!isUpdated)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotModified, $"Sorry, but this Customer (number {customer.ID}) didn't modified")));
            }

            return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, $"The details of the Customer (number {customer.ID}) was updated sucsessfully.")));
        }
Ejemplo n.º 2
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //does the request has username + password?
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "you must sent username and password");
                return;
            }

            //got username and password here in server;

            //how to retrive username and password:
            string autenticationToken = actionContext.Request.Headers.Authorization.Parameter;

            string decodedAutenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(autenticationToken));

            string[] usernamepasswordArr = decodedAutenticationToken.Split(':');
            string   userName            = usernamepasswordArr[0];
            string   password            = usernamepasswordArr[1];


            Utility_class_UserDAOMSSQL <Utility_class_User> utility_class_UserDAO = new Utility_class_UserDAOMSSQL <Utility_class_User>();
            List <Utility_class_User> registeredSystemUsersLst = utility_class_UserDAO.GetAll();

            bool isUserLegal = false;
            Utility_class_User registeredUser = new Utility_class_User();

            foreach (var s in registeredSystemUsersLst)
            {
                if (s.USER_NAME.Length > 50 && s.PASSWORD.Length > 50)
                {
                    if (userName == Statics.Decrypt(s.USER_NAME, ENCRIPTION_PHRASE) && password == Statics.Decrypt(s.PASSWORD, ENCRIPTION_PHRASE))
                    {
                        isUserLegal              = true;
                        registeredUser.PASSWORD  = password;
                        registeredUser.USER_NAME = userName;
                        registeredUser.USER_KIND = s.USER_KIND;
                        break;
                    }
                }
            }


            if (isUserLegal)
            {
                /*
                 * //Also there is an option to put the information in the bag on the Request itself, not on the Principal.
                 * //There is how to put a data on the Request's bag:
                 */
                actionContext.Request.Properties["registered_user"] = registeredUser;
                return;
            }


            //stop the request = will not arive to web api controller
            actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "you are not allowed");
        }
        /// <summary>
        /// If the user credantials are valid, returns true by "return" and instance of "Utility_class_User" with validated unencrypted user name nd password and user role by "out",
        /// in the "USER_NAME", "PASSWORD" and "USER_KIND" properties. Rest of the properties doesn't matter.
        /// In this methos "Utility_class_User" used differently, here it's just a data bearing model for validated user credentials.
        /// If the user credantials are not valid, returns false by "return" and null by "out".
        /// </summary>
        /// <param name="username">username</param>
        /// <param name="password">password</param>
        /// <param name="validatedUserModel">instance of "Utility_class_User" class with validated unecrypted user credentials. In this context used merely as a data bearing model for validated user credentials, only properties "USER_NAME", "PASSWORD" and "USER_KIND" are matters. "USER_KIND" bears user role.</param>
        /// <returns></returns>
        public bool ValidateUser(string username, string password, out Utility_class_User validatedUserModel)
        {
            bool   isUserValid = false;
            string s_USER_NAME = string.Empty;
            string s_PASSWORD  = string.Empty;

            foreach (var s in _registeredUsersLst)
            {
                if (s.USER_NAME.Length > 50)
                {
                    s_USER_NAME = EncryptionProvider.Decryprt(s.USER_NAME);
                }
                else
                {
                    s_USER_NAME = s.USER_NAME;
                }

                if (s.PASSWORD.Length > 50)
                {
                    s_PASSWORD = EncryptionProvider.Decryprt(s.PASSWORD);
                }
                else
                {
                    s_PASSWORD = s.PASSWORD;
                }


                if (username == s_USER_NAME && password == s_PASSWORD)
                {
                    _registeredUser.PASSWORD  = password;
                    _registeredUser.USER_NAME = username;
                    _registeredUser.USER_KIND = s.USER_KIND;
                    isUserValid = true;
                    break;
                }
            }
            if (!isUserValid)
            {
                _registeredUser = null;
            }
            validatedUserModel = _registeredUser;
            return(isUserValid);
        }
        //-------------------------
        public string CreateToken(Utility_class_User validatedUserModel)
        {
            //set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(7);

            //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            var claimsIdentity = new ClaimsIdentity(new[]

            {
                new Claim(ClaimTypes.Name, validatedUserModel.USER_NAME),
                new Claim(ClaimTypes.Role, validatedUserModel.USER_KIND),
                new Claim("Password", validatedUserModel.PASSWORD),
            }

                                                    );


            var signingCredentials = new SigningCredentials(GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256Signature);


            //Create the jwt (JSON Web Token)
            //Replace the issuer and audience with your URL (ex. http:localhost:12345)
            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(
                    issuer: "https://localhost:44361/",
                    audience: "https://localhost:44361/",
                    subject: claimsIdentity,
                    notBefore: issuedAt,
                    expires: expires,
                    signingCredentials: signingCredentials);

            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //got username and password here in server;


            //does the request has username + password?
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "you must sent username and password");
                return;
            }
            //how to retrive username and password:
            string autenticationToken = actionContext.Request.Headers.Authorization.Parameter;

            string decodedAutenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(autenticationToken));

            string[] usernamepasswordArr = decodedAutenticationToken.Split(':');
            string   userName            = usernamepasswordArr[0];
            string   password            = usernamepasswordArr[1];



            /*
             * //Example of using ThreadStatic fields:
             */
            Utility_class_UserDAOMSSQL <Utility_class_User> utility_class_UserDAO = new Utility_class_UserDAOMSSQL <Utility_class_User>();
            List <Utility_class_User> registeredSystemUsersLst = utility_class_UserDAO.GetAll();

            bool isUserLegal = false;
            Utility_class_User registeredUser = new Utility_class_User();

            foreach (var s in registeredSystemUsersLst)
            {
                if (s.USER_NAME.Length > 50 && s.PASSWORD.Length > 50)
                {
                    if (userName == Statics.Decrypt(s.USER_NAME, ENCRIPTION_PHRASE) && password == Statics.Decrypt(s.PASSWORD, ENCRIPTION_PHRASE))
                    {
                        isUserLegal              = true;
                        registeredUser.PASSWORD  = password;
                        registeredUser.USER_NAME = userName;
                        registeredUser.USER_KIND = s.USER_KIND;
                        break;
                    }
                }
            }



            //Principle


            //if username and pasword are legal stop the function and prevent it to return Unauthorized response
            if (isUserLegal)
            {
                /*
                 * // Passing information (aka username) through current thread by putting it in the Principal of the thread.
                 * Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), null);
                 */

                /*
                 * // Passing information (aka username) through the request by putting it in the Principal of the request.
                 *
                 * actionContext.Request.GetRequestContext().Principal = new GenericPrincipal(new GenericIdentity(userName), null);
                 */

                /*
                 * //Also there is an option to putte information in the bag on the Request itself, not on the Principal.
                 * //There is how to put a data on the Request's bag:
                 */

                actionContext.Request.Properties["registered_user"] = registeredUser;
                _registeredUser = registeredUser;

                actionContext.Request.Properties["arbitrary_key"] = usernamepasswordArr; //
                                                                                         //"actionContext.Request.Properties" is a dictionary of objects (Dictionary<string, object>), you can put inside any object with an arbitrary string key key



                return;
            }


            //stop the request = will not arive to web api controller
            actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized, "you are not allowed");
        }