public async Task <HttpResponseMessage> LoginContact([FromBody] LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Response.ModelStateInValid(ModelState));
            }

            ApiResponseModel <LoginModelOutput> apimodel = new ApiResponseModel <LoginModelOutput>();
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                output = await MazikCareService.Core.AzureADB2C.AuthenticateUser(model.UserName, model.Password);

                if (output.success)
                {
                    apimodel.data.records = output;
                }
                else
                {
                    return(Response.Unauthorized("CRM", "Credentials are not Valid"));
                }

                return(Response.Success <LoginModelOutput>(apimodel));
            }
            catch (Exception ex)
            {
                return(Response.Exception(ex));
            }
        }
        public async Task <HttpResponseMessage> getUserToken([FromBody] LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Response.ModelStateInValid(ModelState));
            }

            ApiResponseModel <LoginModelOutput> apimodel = new ApiResponseModel <LoginModelOutput>();
            LoginModelOutput output = new LoginModelOutput();
            string           token  = "";

            try
            {
                output = await MazikCareService.Core.Authentication.AuthenticateUser(model.UserName, model.Password, model.Domain);

                if (output.success)
                {
                    string tokenString = string.Format("{0}:{1}", model.UserName, model.Password);

                    token                 = MazikCareService.Core.Authentication.Base64Encode(tokenString);
                    output.token          = token;
                    apimodel.data.records = output;
                }
                else
                {
                    return(Response.Unauthorized("CRM", "Credentials are not Valid"));
                }

                return(Response.Success <LoginModelOutput>(apimodel));
            }
            catch (Exception ex)
            {
                return(Response.Exception(ex));
            }
        }
Exemple #3
0
        public static async Task <LoginModelOutput> resendSMSCode(string sysUserId, long smsCodeId)
        {
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                SoapEntityRepository repo = SoapEntityRepository.GetService();

                QueryExpression query = new QueryExpression(SystemUser.EntityLogicalName);

                query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("fullname", "mzk_axresourcerefrecid");

                query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, new Guid(sysUserId));

                EntityCollection entitycollection = repo.GetEntityCollection(query);

                Entity entity = entitycollection[0];

                SystemUser user = (SystemUser)entity;

                long resourceRecId = user.mzk_AXResourceRefRecId.HasValue ? Convert.ToInt64(user.mzk_AXResourceRefRecId.Value) : 0;

                if (resourceRecId == 0)
                {
                    throw new ValidationException("Resource Id not set for the user. Please contact system administrator");
                }

                ResourceRepository resourceRepo = new ResourceRepository();
                //HMResourceLoginSMSCodeContract contract = resourceRepo.generateResourceSMSCode(resourceRecId, smsCodeId);

                //if (contract == null)
                //{
                //    throw new ValidationException("Error generating SMS code. Please try again");
                //}

                //if (contract.parmSuccess)
                //{
                //    output.success = true;
                //    output.smsCodeId = contract.parmResourceLoginSMSCodeRecId;
                //    output.userId = sysUserId;
                //    output.errorMessage = "SMS code sent successfully";
                //}
                //else
                //{
                //    output.success = false;
                //    output.doLogout = contract.parmLogOut;
                //    output.errorMessage = contract.parmErrorMessage;
                //}
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(output);
        }
Exemple #4
0
        public static async Task <LoginModelOutput> AuthenticateUser(string username, string password, string domain)
        {
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                HttpContext.Current.Items["username"] = username;
                HttpContext.Current.Items["password"] = password;
                HttpContext.Current.Items["domain"]   = domain;

                SoapEntityRepository repo = SoapEntityRepository.GetService();

                string sysUserId = string.Empty;
                try
                {
                    sysUserId = repo.GetUserId();
                }
                catch (Exception ex)
                {
                    throw new AuthenticationException("Username/Password is incorrect");
                }

                if (sysUserId != null && sysUserId != string.Empty)
                {
                    QueryExpression query = new QueryExpression(SystemUser.EntityLogicalName);

                    query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(true);

                    query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, new Guid(sysUserId));

                    EntityCollection entitycollection = repo.GetEntityCollection(query);

                    Entity entity = entitycollection[0];

                    SystemUser user = (SystemUser)entity;

                    output.fullName = user.FullName;
                    output.success  = true;
                    output.userId   = sysUserId;
                    output.userName = username;
                }
                else
                {
                    output.success = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(output);
        }
        public async Task <HttpResponseMessage> authenticateSMSCode(LoginModel model)
        {
            ApiResponseModel <LoginModelOutput> apimodel = new ApiResponseModel <LoginModelOutput>();
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                output = await MazikCareService.Core.Authentication.authenticateSMSCode(model.sysUserId, model.smsCodeId, model.smsCode);

                apimodel.data.records = output;

                return(Response.Success <LoginModelOutput>(apimodel));
            }
            catch (Exception ex)
            {
                return(Response.Exception(ex));
            }
        }
        public async Task <HttpResponseMessage> getToken()
        {
            ApiResponseModel <LoginModelOutput> apimodel = new ApiResponseModel <LoginModelOutput>();
            LoginModelOutput output = new LoginModelOutput();
            string           token  = "";

            try
            {
                string tokenString = string.Format("{0}:{1}", SoapCredential.UserName, SoapCredential.Password);
                token                 = MazikCareService.Core.Authentication.Base64Encode(tokenString);
                output.token          = token;
                apimodel.data.records = output;
                return(Response.Success <LoginModelOutput>(apimodel));
            }
            catch (Exception ex)
            {
                return(Response.Exception(ex));
            }
        }
        public async static Task <bool> ValidateToken(string authToken)
        {
            try
            {
                LoginModelOutput token = DynamicsCRMOAuth.AuthenticateUser(false, "", "").Result;

                if (token == null || !token.success)
                {
                    throw new AuthenticationException("Error while validating token");
                }

                HttpContext.Current.Items["token"] = token.token;

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemple #8
0
        public async static Task <bool> ValidateToken(string authToken)
        {
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                // string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));

                //Zain -- for Basic scheme
                if (authToken.StartsWith("Basic "))
                {
                    authToken = authToken.Substring("Basic ".Length).Trim();
                }
                //Zain

                string decodedToken = Authentication.Base64Decode(authToken);
                string userName     = decodedToken.Substring(0, decodedToken.IndexOf(":"));
                string password     = decodedToken.Substring(decodedToken.IndexOf(":") + 1);

                // bool result = true;
                output = await Authentication.Authenticate(userName, password, AppSettings.GetByKey("DOMAIN"), true);

                if (output.success)
                {
                    SoapCredential.UserName = userName;
                    SoapCredential.Password = password;
                    SoapCredential.Domain   = AppSettings.GetByKey("DOMAIN");
                    return(true);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(false);
        }
Exemple #9
0
        public IActionResult RefreshToken([FromRoute] string refreshToken)
        {
            LoginModelOutput    _ouput = new LoginModelOutput();
            CheckUserRepository checkUserRepository = new CheckUserRepository();

            try
            {
                bool validToken = checkUserRepository.IsValidToken(refreshToken);
                if (validToken)
                {
                    List <UserModel> collection   = new List <UserModel>((IEnumerable <UserModel>)checkUserRepository.SearchTokenUser(refreshToken));
                    string           tokenNew     = _authservice.TokenNew(refreshToken);
                    string           RefreshToken = GenerateToken();
                    checkUserRepository.updateUserToken(RefreshToken, collection[0].user_id);

                    _ouput.IsSuccess    = true;
                    _ouput.Code         = 200;
                    _ouput.token        = tokenNew;
                    _ouput.RefreshToken = RefreshToken;
                    _ouput.Message      = "Success Refresh Token";
                }
                else
                {
                    _ouput.IsSuccess = false;
                    _ouput.Code      = 422;
                    _ouput.Message   = "token is not Valid";
                }
            }
            catch (Exception ex)
            {
                _ouput.IsSuccess = false;
                _ouput.Code      = 422;
                _ouput.Message   = ex.Message.ToString();
            }

            return(Ok(_ouput));
        }
Exemple #10
0
        public static async Task <LoginModelOutput> Authenticate(string username, string password, string domain, bool fromToken = false)
        {
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                HttpContext.Current.Items["username"] = username;
                HttpContext.Current.Items["password"] = password;
                HttpContext.Current.Items["domain"]   = domain;

                SoapEntityRepository repo = SoapEntityRepository.GetService();

                string sysUserId = string.Empty;
                try
                {
                    sysUserId = repo.GetUserId();
                }
                catch (Exception ex)
                {
                    throw new AuthenticationException("Username/Password is incorrect");
                }

                if (sysUserId != null && sysUserId != string.Empty)
                {
                    if (fromToken)
                    {
                        output.success  = true;
                        output.userId   = sysUserId;
                        output.userName = username;
                    }
                    else
                    {
                        string externalIP = Helper.AppSettings.GetByKey("APPPublicIP");

                        if (externalIP == Authentication.GetUserIp())
                        {
                            QueryExpression query = new QueryExpression(SystemUser.EntityLogicalName);

                            query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("fullname", "mzk_axresourcerefrecid");

                            query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, new Guid(sysUserId));

                            EntityCollection entitycollection = repo.GetEntityCollection(query);

                            Entity entity = entitycollection[0];

                            SystemUser user = (SystemUser)entity;

                            long resourceRecId = user.mzk_AXResourceRefRecId.HasValue ? Convert.ToInt64(user.mzk_AXResourceRefRecId.Value) : 0;

                            if (resourceRecId == 0)
                            {
                                throw new ValidationException("Resource Id not set for the user. Please contact system administrator");
                            }

                            //ResourceRepository resourceRepo = new ResourceRepository();
                            //HMResourceLoginSMSCodeContract contract = resourceRepo.generateResourceSMSCode(resourceRecId, 0);

                            //if (contract == null)
                            //{
                            //    throw new ValidationException("Error generating SMS code. Please try again");
                            //}

                            //if (contract.parmSuccess)
                            //{
                            //    output.success = true;
                            //    output.smsCodeId = contract.parmResourceLoginSMSCodeRecId;
                            //    output.userId = sysUserId;
                            //}
                            //else
                            //{
                            //    throw new ValidationException(contract.parmErrorMessage);
                            //}
                        }
                        else
                        {
                            QueryExpression query = new QueryExpression(SystemUser.EntityLogicalName);

                            query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("fullname", "mzk_axresourcerefrecid", "entityimage");

                            query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, new Guid(sysUserId));

                            LinkEntity position = new LinkEntity(SystemUser.EntityLogicalName, xrm.Position.EntityLogicalName, "positionid", "positionid", JoinOperator.LeftOuter);
                            position.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("name");

                            LinkEntity businessUnit = new LinkEntity(SystemUser.EntityLogicalName, BusinessUnit.EntityLogicalName, "businessunitid", "businessunitid", JoinOperator.Inner);
                            businessUnit.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("name");

                            LinkEntity bookableResource = new LinkEntity(SystemUser.EntityLogicalName, BookableResource.EntityLogicalName, "systemuserid", "userid", JoinOperator.LeftOuter);
                            bookableResource.Columns     = new Microsoft.Xrm.Sdk.Query.ColumnSet(true);
                            bookableResource.EntityAlias = "bookableresource";
                            query.LinkEntities.Add(bookableResource);

                            query.LinkEntities.Add(position);
                            query.LinkEntities.Add(businessUnit);

                            EntityCollection entitycollection = repo.GetEntityCollection(query);

                            Entity entity = entitycollection[0];

                            SystemUser user = (SystemUser)entity;

                            output.fullName = user.FullName;


                            if (entity.Attributes.Contains("bookableresource.bookableresourceid"))
                            {
                                output.resourceId = (entity.Attributes["bookableresource.bookableresourceid"] as AliasedValue).Value.ToString();
                            }
                            //else
                            //{
                            //    throw new ValidationException("User as a Resource not configured");
                            //}

                            if (entity.Attributes.Contains("position1.name"))
                            {
                                output.designation = (entity.Attributes["position1.name"] as AliasedValue).Value.ToString();
                            }

                            if (entity.Attributes.Contains("businessunit2.name"))
                            {
                                output.organization = (entity.Attributes["businessunit2.name"] as AliasedValue).Value.ToString();
                            }

                            output.success  = true;
                            output.userId   = sysUserId;
                            output.userName = username;

                            if (user.EntityImage != null)
                            {
                                output.image = Convert.ToBase64String(user.EntityImage);
                            }

                            output.privileges = User.getPrivileges(sysUserId);
                        }
                    }
                }
                else
                {
                    output.success = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(output);
        }
Exemple #11
0
        public static async Task <LoginModelOutput> authenticateSMSCode(string sysUserId, long smsCodeId, string smsCode)
        {
            LoginModelOutput output = new LoginModelOutput();

            //try
            //{
            //    ResourceRepository resourceRepo = new ResourceRepository();
            //    HMResourceLoginSMSCodeContract contract = resourceRepo.verifyResourceSMSCode(smsCode, smsCodeId);

            //    if (contract == null)
            //    {
            //        throw new ValidationException("Error verifying SMS code. Please try again");
            //    }

            //    if (contract.parmSuccess)
            //    {
            //        output.smsCodeId = contract.parmResourceLoginSMSCodeRecId;

            //        SoapEntityRepository repo = SoapEntityRepository.GetService();

            //        QueryExpression query = new QueryExpression(SystemUser.EntityLogicalName);

            //        query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("fullname", "mzk_axresourcerefrecid");

            //        query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, new Guid(sysUserId));

            //        LinkEntity position = new LinkEntity(SystemUser.EntityLogicalName, xrm.Position.EntityLogicalName, "positionid", "positionid", JoinOperator.LeftOuter);
            //        position.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("name");

            //        LinkEntity businessUnit = new LinkEntity(SystemUser.EntityLogicalName, BusinessUnit.EntityLogicalName, "businessunitid", "businessunitid", JoinOperator.Inner);
            //        businessUnit.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("name");

            //        query.LinkEntities.Add(position);
            //        query.LinkEntities.Add(businessUnit);

            //        EntityCollection entitycollection = repo.GetEntityCollection(query);

            //        Entity entity = entitycollection[0];

            //        SystemUser user = (SystemUser)entity;

            //        output.fullName = user.FullName;
            //        output.resourceRecId = user.mzk_AXResourceRefRecId.HasValue ? Convert.ToInt64(user.mzk_AXResourceRefRecId.Value).ToString() : "";

            //        if (entity.Attributes.Contains("position1.name"))
            //            output.designation = (entity.Attributes["position1.name"] as AliasedValue).Value.ToString();

            //        if (entity.Attributes.Contains("businessunit2.name"))
            //            output.organization = (entity.Attributes["businessunit2.name"] as AliasedValue).Value.ToString();

            //        output.success = true;
            //        output.userId = sysUserId;

            //        output.privileges = User.getPrivileges(sysUserId);

            //        if (HttpContext.Current.Request.Headers["Authorization"] != null)
            //        {
            //            output.token = HttpContext.Current.Request.Headers["Authorization"].ToString();
            //        }
            //    }
            //    else
            //    {
            //        output.success = false;
            //        output.doLogout = contract.parmLogOut;
            //        output.errorMessage = contract.parmErrorMessage;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}

            return(output);
        }
        public static async Task <LoginModelOutput> AuthenticateUser(string username, string password)
        {
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                using (var client = new HttpClient(new HttpClientHandler()))
                {
                    var content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("username", username),
                        new KeyValuePair <string, string>("password", password),
                        new KeyValuePair <string, string>("grant_type", "password"),
                        new KeyValuePair <string, string>("scope", "openid " + AppSettings.GetByKey("AzureADB2CClientID") + " offline_access"),
                        new KeyValuePair <string, string>("client_id", AppSettings.GetByKey("AzureADB2CClientID")),
                        new KeyValuePair <string, string>("response_type", "token id_token")
                    });
                    var result = client.PostAsync(AppSettings.GetByKey("AzureADB2CURL"), content).Result;

                    if (result != null && result.IsSuccessStatusCode && result.Content != null)
                    {
                        string resultContent = result.Content.ReadAsStringAsync().Result;

                        dynamic ret = JsonConvert.DeserializeObject(resultContent);

                        if (ret != null && ret.access_token != null)
                        {
                            var handler   = new JwtSecurityTokenHandler();
                            var jsonToken = handler.ReadToken(ret.access_token.Value);

                            List <System.Security.Claims.Claim> claimList = jsonToken.Claims;

                            System.Security.Claims.Claim oid = claimList.Where(item => item.Type == "oid").FirstOrDefault();

                            if (oid != null)
                            {
                                LoginModelOutput token = DynamicsCRMOAuth.AuthenticateUser(false, "", "").Result;

                                if (token == null || !token.success)
                                {
                                    output.success = false;
                                    throw new AuthenticationException("Error while generating token");
                                }

                                SoapEntityRepository repo = SoapEntityRepository.GetService();

                                QueryExpression query = new QueryExpression("contact");
                                query.Criteria.AddCondition("mzk_appobjectid", ConditionOperator.Equal, oid.Value);

                                EntityCollection collection = repo.GetEntityCollection(query);

                                if (collection != null && collection.Entities != null && collection.Entities.Count > 0)
                                {
                                    output.userId  = collection.Entities[0].Id.ToString();
                                    output.token   = token.token;
                                    output.success = true;
                                }
                                else
                                {
                                    output.success = false;
                                    throw new AuthenticationException("User is not a registered user");
                                }
                            }
                            else
                            {
                                output.success = false;
                                throw new AuthenticationException("User is not a registered user");
                            }
                        }
                        else
                        {
                            output.success = false;
                            throw new AuthenticationException("Username/Password is incorrect");
                        }
                    }
                    else
                    {
                        output.success = false;
                        throw new AuthenticationException("Username/Password is incorrect");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(output);
        }
Exemple #13
0
        public ActionResult Login([FromBody] LoginRequestModel request)
        {
            LoginModelOutput _ouput = new LoginModelOutput();

            try
            {
                if (ModelState.IsValid)
                {
                    string token;
                    if (_authservice.IsAuthenticated(request, out token))
                    {
                        DisplayUserSecurityRepository displayUserSecurity = new DisplayUserSecurityRepository();
                        CheckUserRepository           checkUserRepository = new CheckUserRepository();

                        List <UserModel> collection = new List <UserModel>((IEnumerable <UserModel>)displayUserSecurity.SearchUserWithSetting(request.Email));

                        string refreshToken = GenerateToken();

                        checkUserRepository.InsertLogToken(request.Email, refreshToken, collection[0].user_id);
                        checkUserRepository.updateUserToken(refreshToken, collection[0].user_id);


                        _ouput.IsSuccess    = true;
                        _ouput.Code         = 200;
                        _ouput.Message      = "Success Login";
                        _ouput.Data         = collection.ToList();
                        _ouput.token        = token;
                        _ouput.RefreshToken = refreshToken;
                    }
                    else
                    {
                        _ouput.IsSuccess = false;
                        _ouput.Code      = 422;
                        _ouput.Message   = "Username And Password Is Not Match";
                    }
                }
                else
                {
                    string errordetails = "";
                    var    errors       = new List <string>();
                    foreach (var state in ModelState)
                    {
                        foreach (var error in state.Value.Errors)
                        {
                            string p = error.ErrorMessage;
                            errordetails = errordetails + error.ErrorMessage;
                        }
                    }
                    Dictionary <string, object> dict = new Dictionary <string, object>();
                    dict.Add("error", errordetails);

                    _ouput.IsSuccess   = false;
                    _ouput.Message     = "error login";
                    _ouput.Code        = 422;
                    _ouput.CustomField = dict;
                }
            }
            catch (Exception ex)
            {
                _ouput.IsSuccess = false;
                _ouput.Code      = 422;
                _ouput.Message   = ex.Message.ToString();
            }

            return(Ok(_ouput));
        }
        public static async Task <LoginModelOutput> AuthenticateUser(bool validateUser, string username, string password)
        {
            LoginModelOutput output = new LoginModelOutput();

            try
            {
                string crmUrl       = AppSettings.GetByKey("CRMAPI");
                string clientId     = AppSettings.GetByKey("CRMClientID");
                string clientSecret = AppSettings.GetByKey("CRMClientSecret");

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(crmUrl)).Result;

                String authorityUrl = ap.Authority;
                String resource     = ap.Resource;


                AuthenticationResult result = null;

                AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false);

                if (validateUser)
                {
                    UserCredential userCredential = new UserPasswordCredential(username, password);
                    result = authContext.AcquireTokenAsync(resource, clientId, userCredential).Result;
                }
                else
                {
                    ClientCredential credential = new ClientCredential(clientId, clientSecret);
                    result = authContext.AcquireTokenAsync(resource, credential).Result;
                }

                if (result != null)
                {
                    output.token = result.AccessToken;
                    HttpContext.Current.Items["token"] = result.AccessToken;

                    if (validateUser)
                    {
                        SoapEntityRepository repo = SoapEntityRepository.GetService();

                        output.userId = repo.GetUserId();
                    }

                    output.success = true;
                }
                else
                {
                    output.success = false;

                    if (validateUser)
                    {
                        throw new AuthenticationException("Username/Password is incorrect");
                    }
                    else
                    {
                        throw new AuthenticationException("Application user is not setup");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(output);
        }