Esempio n. 1
0
        private async Task GenerateToken(HttpContext context)
        {
            var username = context.Request.Form["username"];
            var password = context.Request.Form["password"];

            var identity = await _options.IdentityResolver(username, password);

            if (identity == null)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid username or password.");

                return;
            }

            var now = DateTime.UtcNow;


            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, username),
                new Claim(JwtRegisteredClaimNames.Jti, await _options.NonceGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
            };

            // Create the JWT and write it to a string
            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                signingCredentials: _options.SigningCredentials);
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);


            var response = new
            {
                access_token = encodedJwt,
                expires_in   = (int)_options.Expiration.TotalSeconds
            };

            // Serialize and return the response
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
        }
        private async Task GenerateToken(HttpContext context)
        {
            //var username = context.Request.Form["username"]; //admin
            //var password = context.Request.Form["password"]; //gwtsoft
            //var _loginType = context.Request.Form["LoginType"];
            LoginDataModel loginData  = new LoginDataModel();
            string         username   = "";
            string         password   = "";
            string         _loginType = "";
            string         MemberID   = "";
            string         MemberNo   = "";

            try
            {
                using (var reader = new System.IO.StreamReader(context.Request.Body))
                {
                    var request_body = reader.ReadToEnd();
                    loginData = JsonConvert.DeserializeObject <LoginDataModel>(request_body, _serializerSettings);
                    if (loginData.username == null)
                    {
                        loginData.username = "";
                    }
                    if (loginData.password == null)
                    {
                        loginData.password = "";
                    }
                    if (loginData.LoginType == null)
                    {
                        loginData.LoginType = "";
                    }
                    username   = loginData.username;
                    password   = loginData.password;
                    _loginType = loginData.LoginType;
                }
            }
            catch (Exception ex)
            {
                string error = ex.Message;
            }

            string ipaddress = "127.0.0.1";

            // set ipaddress
            if (context.Connection.RemoteIpAddress != null)
            {
                ipaddress = context.Connection.RemoteIpAddress.ToString();
            }

            string clienturl = context.Request.Headers["Referer"];

            dynamic result        = null;
            string  ipaddresslist = "";


            if (_loginType == "1")
            {
                result = doAdminTypeloginValidation(username, password, clienturl, ipaddress);

                if (result == null || result.Count <= 0)
                {
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsync("Invalid username or password.");

                    return;
                }
                if (result[0].access_status == 1)
                {
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsync("This user account is deleted.");

                    return;
                }

                if (result[0].access_status == 2)
                {
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsync("This user account is locked.Please check your email to unlock your account!!!");

                    return;
                }
                ipaddresslist = result[0].restricted_iplist;
            }
            else if (_loginType == "2")
            {
                result = doCustomerTypeloginValidation(username, password, clienturl, ipaddress);
                if (result == null || result.Count <= 0)
                {
                    context.Response.StatusCode = 400;
                    string Message     = "Invalid username or password.";
                    var    objresponse = new { status = 0, messages = Message };
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(objresponse));

                    // await context.Response.WriteAsync("Invalid username or password.");
                    return;
                }
                if (result[0].access_status == 1)
                {
                    context.Response.StatusCode = 400;
                    string Message     = "This user account is deleted.";
                    var    objresponse = new { status = 0, messages = Message };
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(objresponse));

                    // await context.Response.WriteAsync("This user account is deleted.");
                    return;
                }

                if (result[0].access_status == 2)
                {
                    context.Response.StatusCode = 400;
                    string Message     = "This user account is locked.Please check your email to unlock your account!!!";
                    var    objresponse = new { status = 0, messages = Message };
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(objresponse));

                    // await context.Response.WriteAsync("This user account is locked.Please check your email to unlock your account!!!");
                    return;
                }
            }
            else
            {
                // result = (_repository.Member.GetMemberLoginValidation(username)).ToList();

                if (result.Count > 0)
                {
                    MemberID = result[0].memberID.ToString();
                    MemberNo = result[0].memberNo;
                }
                if (result == null || result.Count <= 0)
                {
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsync("Invalid username or password.");

                    return;
                }
                if (result[0].access_status == 1)
                {
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsync("This user account is deleted.");

                    return;
                }

                if (result[0].access_status == 2)
                {
                    context.Response.StatusCode = 400;
                    await context.Response.WriteAsync("This user account is locked.Please check your email to unlock your account!!!");

                    return;
                }
            }


            Boolean sameip = true;

            if (ipaddresslist != "" && ipaddresslist != null)
            {
                sameip = false;
                string[] ipaddressarr = ipaddresslist.Split(',');
                for (int ip_index = 0; ip_index < ipaddressarr.Length; ip_index++)
                {
                    if (ipaddress == ipaddressarr[ip_index].Trim())
                    {
                        sameip = true;
                        break;
                    }
                }
            }
            if (sameip == false)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Your IP Address is invalid for this account.");

                return;
            }

            if (_loginType == "1")
            {
                string userID     = result[0].AdminID.ToString();
                var    now        = DateTime.UtcNow;
                var    _tokenData = new TokenData();
                _tokenData.Sub = result[0].AdminName;
                _tokenData.Jti = await _options.NonceGenerator();

                _tokenData.Iat         = new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString();
                _tokenData.UserID      = userID;
                _tokenData.Userlevelid = result[0].AdminLevelID.ToString();
                //_tokenData.CompanyID = result[0].CompanyID;
                // _tokenData.branchID = result[0].branchID;
                _tokenData.LoginType        = _loginType.ToString();
                _tokenData.TicketExpireDate = now.Add(_options.Expiration);
                var claims = Globalfunction.GetClaims(_tokenData);

                // Create the JWT and write it to a string
                var jwt = new JwtSecurityToken(
                    issuer: _options.Issuer,
                    audience: _options.Audience,
                    claims: claims,
                    notBefore: now,
                    expires: now.Add(_options.Expiration),
                    signingCredentials: _options.SigningCredentials);
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                var settingresult = (_repository.Setting.GetPasswordValidation()).ToList();
                var pwdlength     = settingresult[0].Value;

                var response = new
                {
                    access_token = encodedJwt,
                    expires_in   = (int)_options.Expiration.TotalSeconds,
                    UserID       = userID,
                    LoginType    = _loginType,
                    userLevelID  = result[0].AdminLevelID,
                    displayName  = result[0].AdminName,
                    CompanyID    = result[0].CompanyID,
                    //branchID = result[0].branchID,
                    MemberID  = MemberID,
                    userImage = result[0].ImagePath,
                    PWDLength = pwdlength.ToString()
                };
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
            }
            else if (_loginType == "2")
            {
                string userID     = result[0].customerID.ToString();
                var    now        = DateTime.UtcNow;
                var    _tokenData = new TokenData();
                _tokenData.Sub = result[0].customername;
                _tokenData.Jti = await _options.NonceGenerator();

                _tokenData.Iat    = new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString();
                _tokenData.UserID = userID;
                // _tokenData.branchID = result[0].branchID;
                _tokenData.LoginType        = _loginType.ToString();
                _tokenData.TicketExpireDate = now.Add(_options.Expiration);
                var claims = Globalfunction.GetClaims(_tokenData);

                // Create the JWT and write it to a string
                var jwt = new JwtSecurityToken(
                    issuer: _options.Issuer,
                    audience: _options.Audience,
                    claims: claims,
                    notBefore: now,
                    expires: now.Add(_options.Expiration),
                    signingCredentials: _options.SigningCredentials);
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                var settingresult = (_repository.Setting.GetPasswordValidation()).ToList();
                var pwdlength     = settingresult[0].Value;

                var response = new
                {
                    access_token = encodedJwt,
                    expires_in   = (int)_options.Expiration.TotalSeconds,
                    UserID       = userID,
                    LoginType    = Convert.ToInt32(_loginType),
                    displayName  = result[0].customername,
                    CustomerID   = result[0].customerID,
                    LoginName    = result[0].username,
                    Customercode = result[0].customercode,
                    PWDLength    = pwdlength.ToString()
                };

                var objresponse = new { status = 1, messages = "success", data = response };

                context.Response.ContentType = "application/json";
                // await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
                await context.Response.WriteAsync(JsonConvert.SerializeObject(objresponse, _serializerSettings));
            }
            else
            {
                string memberID   = result[0].memberID.ToString();
                var    now        = DateTime.UtcNow;
                var    _tokenData = new TokenData();
                _tokenData.Sub = result[0].memberName;
                _tokenData.Jti = await _options.NonceGenerator();

                _tokenData.Iat    = new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString();
                _tokenData.UserID = memberID;

                // _tokenData.Userlevelid = result[0].AdminLevelID.ToString();
                //_tokenData.LoginType = _loginType.ToString();
                _tokenData.TicketExpireDate = now.Add(_options.Expiration);
                var claims = Globalfunction.GetClaims(_tokenData);

                // Create the JWT and write it to a string
                var jwt = new JwtSecurityToken(
                    issuer: _options.Issuer,
                    audience: _options.Audience,
                    claims: claims,
                    notBefore: now,
                    expires: now.Add(_options.Expiration),
                    signingCredentials: _options.SigningCredentials);
                var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

                var settingresult = (_repository.Setting.GetPasswordValidation()).ToList();
                var pwdlength     = settingresult[0].Value;

                var response = new
                {
                    access_token = encodedJwt,
                    expires_in   = (int)_options.Expiration.TotalSeconds,
                    // UserID = userID,
                    // LoginType = _loginType,
                    // userLevelID = result[0].AdminLevelID,
                    displayName = result[0].memberName,
                    MemberID    = MemberID,
                    MemberNo    = MemberNo,
                    //userImage = result[0].ImagePath,
                    PWDLength = pwdlength.ToString()
                };
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings));
            }


            // Serialize and return the response
        }