Exemplo n.º 1
0
        public IActionResult PostUsers([FromBody] UserTokenResult token)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            DateTime now = DateTime.UtcNow;

            if (token == null)
            {
                return(BadRequest(new DataError("securityErr", "No authorization controll.")));
            }
            UserToken dbtoken = Security.CheckUserToken(this._context, token);

            if (dbtoken == null)
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            else
            {
                if (!dbtoken.IsTimeValid(now))
                {
                    return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required.")));
                }
                else
                {
                    dbtoken.UpdateToken(now);
                }
            }
            string email = _context.Users.FirstOrDefault(e => e.Name == dbtoken.UserName).Email;

            return(Ok(new { success = true, email }));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> PostTokens([FromBody] LoginToken token)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            DateTime time = DateTime.UtcNow;

            if (!TokensExists(token.TokenName, out Tokens dbtoken))
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            if (!IsTokenValid(token, dbtoken, time))
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            if (!dbtoken.IsTimeValid(time))
            {
                _context.Tokens.Remove(dbtoken);
                return(BadRequest(new DataError("tokenErr", "Relogin is required. Autologin has timedout.")));
            }

            UserToken usertoken = Security.GenerateUsersToken(dbtoken.UserName, this._context);

            dbtoken.UpdateToken(time);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                return(BadRequest(new DataError("tokenErr", "Failed to remember login.")));
            }
            PernamentTokenResult result = new PernamentTokenResult()
            {
                Token      = dbtoken.HashedToken,
                TokenName  = dbtoken.TokenName,
                ExpireDate = dbtoken.ExpireDate,
            };
            UserTokenResult userResult = new UserTokenResult()
            {
                Token    = usertoken.HashedToken,
                UserName = usertoken.UserName,
            };
            var h = _context.Heros.Join(_context.UsersHeros.Where(e => e.UserName == dbtoken.UserName), e => e.HeroId, e => e.HeroId, (a, b) => new HeroBrief()
            {
                Name     = a.Name,
                Nickname = a.Nickname,
                Level    = a.Lvl,
                Orders   = a.Orders,
            });

            return(Ok(new { success = true, usertoken = userResult, logintoken = result, user = new UserBrief()
                            {
                                Username = dbtoken.UserName, Characters = h.ToArray()
                            } }));
        }
        public async Task <IActionResult> PostTokens([FromBody] PassedData <string> passedData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            DateTime now = DateTime.UtcNow;

            if (passedData.UserToken == null)
            {
                return(BadRequest(new DataError("securityErr", "No authorization controll.")));
            }
            UserToken dbtoken = Security.CheckUserToken(this._context, passedData.UserToken);

            if (dbtoken == null)
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            else
            {
                if (!dbtoken.IsTimeValid(now))
                {
                    return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required.")));
                }
                else
                {
                    dbtoken.UpdateToken(now);
                }
            }
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                return(BadRequest(new DataError("databaseErr", "Failed to update tokens.")));
            }
            UserTokenResult userResult = new UserTokenResult()
            {
                Token    = dbtoken.HashedToken,
                UserName = dbtoken.UserName,
            };
            var h = _context.Heros.Join(_context.UsersHeros.Where(e => e.UserName == dbtoken.UserName), e => e.HeroId, e => e.HeroId, (a, b) => new HeroBrief()
            {
                Name     = a.Name,
                Nickname = a.Nickname,
                Level    = a.Lvl,
                Orders   = a.Orders,
            });

            return(Ok(new { success = true, usertoken = userResult, user = new UserBrief()
                            {
                                Username = dbtoken.UserName, Characters = h.ToArray()
                            } }));
        }
Exemplo n.º 4
0
        private UserTokenResult Token(AccountEntity model)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var key            = Encoding.UTF8.GetBytes(_jwtSettings.SecretKey);
            var authTime       = DateTime.Now;         //授权时间
            var expiresAt      = authTime.AddDays(30); //过期时间
            var tokenDescripor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(JwtClaimTypes.Audience, _jwtSettings.Audience),
                    new Claim(JwtClaimTypes.Issuer, _jwtSettings.Issuer),
                    new Claim(JwtClaimTypes.Name, model.LoginName),

                    new Claim(Zoomtel.Service.Auth.ClaimTypes.LoginName, model.LoginName),
                    new Claim(Zoomtel.Service.Auth.ClaimTypes.Uid, model.Uid.ToString()),
                    new Claim(Zoomtel.Service.Auth.ClaimTypes.LoginTime, authTime.ToString())

                    //new Claim(JwtClaimTypes.Name, model.LoginName),
                    //new Claim(JwtClaimTypes.Id, model.Uid.ToString())
                }),
                Expires = expiresAt,
                //对称秘钥SymmetricSecurityKey
                //签名证书(秘钥,加密算法)SecurityAlgorithms
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var             token       = tokenHandler.CreateToken(tokenDescripor);
            var             tokenString = tokenHandler.WriteToken(token);
            UserTokenResult result      = new UserTokenResult();

            result.access_token = tokenString;
            result.expires_at   = expiresAt;
            result.name         = model.LoginName;
            result.uid          = model.Uid.ToString("N");

            return(result);
        }
Exemplo n.º 5
0
        private void btnUserRegister_Click(object sender, EventArgs e)
        {
            _Thread_UserRegister = new Thread(() =>
            {
                btnUserRegister.Enabled = false;

                #region Parameters/Headers
                IDictionary <string, string> SendParams = new Dictionary <string, string>()
                {
                };
                IDictionary <string, string> SendHeaders = ProcessSendHeaders();

                SendParams.Add("UserName", txtLoginUser.Text.Trim());
                SendParams.Add("Password", WinFun.StringToBase64(txtLoginPassword.Text.Trim()));
                SendParams.Add("MobileCode", txtLoginMobileCode.Text.Trim());
                SendParams.Add("VerifyKey", txtVerifyKey.Text.Trim());
                SendParams.Add("VerifyCode", txtLoginVerifyCode.Text.Trim());
                #endregion

                #region Process & Results
                bool IsSucceed = ProcessHTTPSend(GetHTTPSendURL((int)APIActionType.UserRegister), SendParams, SendHeaders, out string OutMessages, out string OutHtmlSource);
                if (IsSucceed && OutHtmlSource.Length > 0)
                {
                    UserTokenResult ResultInfo           = null;
                    UserTokenResultError ResultInfoError = null;

                    try { ResultInfo = JsonConvert.DeserializeObject <UserTokenResult>(OutHtmlSource); }
                    catch { }

                    try { ResultInfoError = JsonConvert.DeserializeObject <UserTokenResultError>(OutHtmlSource); }
                    catch { }

                    if (ResultInfo != null)
                    {
                        if (ResultInfo.StateCode.Equals(1))
                        {
                            //txtParamV1.Text = ResultInfo.Info.Token;
                            //txtHeaderV1.Text = ResultInfo.Info.Token;
                            WinFun.ShowMessageBox("注册成功");
                        }
                        else
                        {
                            WinFun.ShowMessageBox("注册失败," + ResultInfo.StateMessage);
                        }
                    }
                    else
                    {
                        if (ResultInfoError != null)
                        {
                            StringBuilder SbResults = new StringBuilder();
                            foreach (var item in ResultInfoError.Info)
                            {
                                SbResults.Append(item.Code.ToString() + ":" + item.Message + "\r");
                            }

                            WinFun.ShowMessageBox("注册失败,\r" + SbResults.ToString());
                        }
                        else
                        {
                            WinFun.ShowMessageBox("注册失败,远程返回状态不正确");
                        }
                    }
                }
                else
                {
                    WinFun.ShowMessageBox(OutMessages);
                }
                #endregion

                btnUserRegister.Enabled = true;
            });
            _Thread_UserRegister.Start();
        }
Exemplo n.º 6
0
        public async Task <IActionResult> PostUsers([FromBody] LoginUser user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (UsersExists(user.Name) && PasswordMatches(user.Name, user.Password))
            {
                UserToken usertoken = Security.GenerateUsersToken(user.Name, this._context);
                Tokens    token     = null;
                if (user.isRemembered)
                {
                    token = GenerateUsersPernamentToken(user);
                }
                try
                {
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateException)
                {
                    return(BadRequest(new DataError("tokenErr", "Failed to remember login.")));
                }

                PernamentTokenResult result = null;
                if (user.isRemembered)
                {
                    result = new PernamentTokenResult()
                    {
                        Token      = token.HashedToken,
                        TokenName  = token.TokenName,
                        ExpireDate = token.ExpireDate,
                    };
                }
                UserTokenResult userResult = new UserTokenResult()
                {
                    Token    = usertoken.HashedToken,
                    UserName = usertoken.UserName,
                };

                var h = _context.Heros.Join(_context.UsersHeros.Where(e => e.UserName == user.Name), e => e.HeroId, e => e.HeroId, (a, b) => new HeroBrief()
                {
                    Name     = a.Name,
                    Nickname = a.Nickname,
                    Level    = a.Lvl,
                    Orders   = a.Orders,
                });

                if (user.isRemembered)
                {
                    return(Ok(new { success = true, usertoken = userResult, logintoken = result, user = new UserBrief()
                                    {
                                        Username = user.Name, Characters = h.ToArray()
                                    } }));
                }
                else
                {
                    return(Ok(new { success = true, usertoken = userResult, user = new UserBrief()
                                    {
                                        Username = user.Name, Characters = h.ToArray()
                                    } }));
                }
            }
            else
            {
                return(BadRequest(new DataError("loginErr", "Invalid login or password.")));
            }
        }