コード例 #1
0
ファイル: RegisterController.cs プロジェクト: Romonov/Mimir
 public IActionResult Register([FromForm] RegisterModel model)
 {
     ViewData["ServerName"] = Program.ServerName;
     ViewData["Title"]      = "注册";
     if (ModelState.IsValid)
     {
         if (model.VerificationCode == HttpContext.Session.GetString("VerificationCode"))
         {
             var time     = TimeWorker.GetTimeStamp10();
             var password = HashWorker.HashPassword(model.Password, time);
             db.Users.Add(new Users()
             {
                 Username          = model.Username,
                 Email             = model.Email,
                 Password          = password,
                 PreferredLanguage = "zh_CN",
                 CreateIp          = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(),
                 CreateTime        = time,
                 PermissionLevel   = 0,
                 IsEmailVerified   = 1
             });
             db.SaveChanges();
             return(RedirectToAction(actionName: "Index", controllerName: "User"));
         }
         else
         {
             ModelState.AddModelError(string.Empty, "验证码不正确!");
             return(View("Index", model));
         }
     }
     return(View("Index", model));
 }
コード例 #2
0
        public JsonResult Join([FromBody] PostJoinRequest request)
        {
            // Check token.
            var tokens = from t in db.Tokens where t.AccessToken == request.accessToken && t.Status == 2 select t;

            if (tokens.Count() != 1)
            {
                return(new JsonResult(ExceptionWorker.InvalidToken())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }
            var token = tokens.First();

            // Check profile.
            var profiles = from p in db.Profiles where p.Uuid == request.selectedProfile select p;

            if (profiles.Count() != 1)
            {
                return(new JsonResult(ExceptionWorker.InvalidToken())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }
            var profile = profiles.First();

            if (token.BindProfileId != profile.Id)
            {
                return(new JsonResult(ExceptionWorker.InvalidToken())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            db.Sessions.Add(new Sessions()
            {
                AccessToken = request.accessToken,
                ServerId    = request.serverId,
                ExpireTime  = TimeWorker.GetTimeStamp10(Program.SessionsExpireSeconds),
                ClientIp    = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString()
            });
            db.SaveChanges();

            // Clean expired sessions.
            var time     = long.Parse(TimeWorker.GetTimeStamp10());
            var sessions = from s in db.Sessions where long.Parse(s.ExpireTime) < time select s;

            foreach (var item in sessions)
            {
                db.Sessions.Remove(item);
            }
            db.SaveChanges();

            log.Info($"[ID: {HttpContext.Connection.Id}]Player {profile.Name} with IP {HttpContext.Connection.RemoteIpAddress.MapToIPv4()}:{HttpContext.Connection.RemotePort} tried to login server.");

            return(new JsonResult(null)
            {
                StatusCode = (int)HttpStatusCode.NoContent
            });
        }
コード例 #3
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            TimeWorker.RunWorkerAsync();
            MainPanel.Controls.Clear();
            UserSearchForm searchForm = new UserSearchForm(this);

            searchForm.TopLevel = false;
            searchForm.Dock     = DockStyle.Fill;
            MainPanel.Controls.Add(searchForm);
            searchForm.Show();
        }
コード例 #4
0
        private void AdminMainForm_Load(object sender, EventArgs e)
        {
            TimeWorker.RunWorkerAsync();
            MainPanel.Controls.Clear();
            AdminFunctionForm adminFunctionForm = new AdminFunctionForm(this);

            adminFunctionForm.TopLevel = false;
            adminFunctionForm.Dock     = DockStyle.Fill;
            MainPanel.Controls.Add(adminFunctionForm);
            adminFunctionForm.Show();
        }
コード例 #5
0
        public JsonResult HasJoined()
        {
            string username = Request.Query["username"];
            string serverId = Request.Query["serverId"];
            string ip       = Request.Query["ip"];

            if (username == null || username == string.Empty || serverId == null || serverId == string.Empty)
            {
                return(new JsonResult(null)
                {
                    StatusCode = (int)HttpStatusCode.NoContent
                });
            }

            var profiles = from p in db.Profiles where p.Name == username select p;

            if (profiles.Count() != 1)
            {
                return(new JsonResult(null)
                {
                    StatusCode = (int)HttpStatusCode.NoContent
                });
            }
            var profile = profiles.First();

            var tokens = from t in db.Tokens where t.BindProfileId == profile.Id && t.Status == 2 select t;

            if (tokens.Count() < 1)
            {
                return(new JsonResult(null)
                {
                    StatusCode = (int)HttpStatusCode.NoContent
                });
            }
            var token = tokens.First();

            var time = long.Parse(TimeWorker.GetTimeStamp10());
            IQueryable <Sessions> sessions = null;

            if (ip != null && ip != string.Empty)
            {
                sessions = from s in db.Sessions where long.Parse(s.ExpireTime) >= time && s.AccessToken == token.AccessToken && s.ServerId == serverId && s.ClientIp == ip select s;
            }
            else
            {
                sessions = from s in db.Sessions where long.Parse(s.ExpireTime) >= time && s.AccessToken == token.AccessToken && s.ServerId == serverId select s;
            }
            if (sessions.Count() < 1)
            {
                return(new JsonResult(null)
                {
                    StatusCode = (int)HttpStatusCode.NoContent
                });
            }

            var result = ProfileWorker.GetProfile(db, profile.Name, true, false);

            if (result != null)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]Player {profile.Name} login successfully.");
                return(new JsonResult(result.Value));
            }
            else
            {
                return(new JsonResult(null)
                {
                    StatusCode = (int)HttpStatusCode.NoContent
                });
            }
        }
コード例 #6
0
        public JsonResult Signout([FromBody] PostSignoutRequest request)
        {
            log.Info($"[ID: {HttpContext.Connection.Id}]Got logout request from {HttpContext.Connection.RemoteIpAddress.MapToIPv4()}:{HttpContext.Connection.RemotePort} with user {request.username}.");

            // Check if user exists.
            var users = from u in db.Users where u.Email == request.username select u;

            if (users.Count() != 1)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]Request user is not exists.");
                return(new JsonResult(ExceptionWorker.InvalidUsername())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Cooldown check.
            var user      = users.First();
            var time      = TimeWorker.GetTimeStamp10();
            var cooldowns = from c in db.Cooldown where c.Uid == user.Id select c;

            if (cooldowns.Count() != 1)
            {
                db.Cooldown.Add(new Cooldown()
                {
                    Uid           = user.Id,
                    TryTimes      = 0,
                    LastTryTime   = time,
                    LastLoginTime = user.CreateTime,
                    CooldownLevel = 0,
                    CooldownTime  = time
                });
                db.SaveChanges();
            }

            cooldowns = from c in db.Cooldown where c.Uid == user.Id select c;
            var cooldown = cooldowns.First();

            if (Convert.ToDecimal(cooldown.CooldownTime) > Convert.ToDecimal(time))
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} already in cooldown.");
                return(new JsonResult(ExceptionWorker.TooManyTryTimes())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }
            else
            {
                if (cooldown.TryTimes >= Program.SecurityLoginTryTimes)
                {
                    cooldown.CooldownLevel++;
                    cooldown.CooldownTime = time + cooldown.CooldownLevel * cooldown.CooldownLevel * 5 * 60;
                    db.SaveChanges();
                    log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} got into cooldown.");
                    return(new JsonResult(ExceptionWorker.TooManyTryTimes())
                    {
                        StatusCode = (int)HttpStatusCode.Forbidden
                    });
                }
                cooldown.LastTryTime = time;
                cooldown.TryTimes++;
                db.SaveChanges();
            }

            // Password check.
            var salt           = user.CreateTime;
            var passwordHashed = HashWorker.HashPassword(request.password, salt);

            if (user.Password != passwordHashed)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]IP address {HttpContext.Connection.RemoteIpAddress}:{HttpContext.Connection.RemotePort} try to login with user {request.username} but wrong password.");
                return(new JsonResult(ExceptionWorker.InvalidPassword())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Update cooldown.
            cooldown.LastLoginTime = time;
            cooldown.TryTimes      = 0;
            db.SaveChanges();
            log.Info($"[ID: {HttpContext.Connection.Id}]Cooldown of user {user.Username} has reseted.");

            return(new JsonResult(null)
            {
                StatusCode = (int)HttpStatusCode.NoContent
            });
        }
コード例 #7
0
        public JsonResult Authenticate([FromBody] PostAuthrnticateRequest request)
        {
            log.Info($"[ID: {HttpContext.Connection.Id}]Got login request from {HttpContext.Connection.RemoteIpAddress.MapToIPv4()}:{HttpContext.Connection.RemotePort} with user {request.username}.");

            // Check if user exists.
            var users = from u in db.Users where u.Email == request.username select u;

            if (users.Count() != 1)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]Request user is not exists.");
                return(new JsonResult(ExceptionWorker.InvalidUsername())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Cooldown check.
            var user      = users.First();
            var time      = TimeWorker.GetTimeStamp10();
            var cooldowns = from c in db.Cooldown where c.Uid == user.Id select c;

            if (cooldowns.Count() != 1)
            {
                db.Cooldown.Add(new Cooldown()
                {
                    Uid           = user.Id,
                    TryTimes      = 0,
                    LastTryTime   = time,
                    LastLoginTime = user.CreateTime,
                    CooldownLevel = 0,
                    CooldownTime  = time
                });
                db.SaveChanges();
            }

            cooldowns = from c in db.Cooldown where c.Uid == user.Id select c;
            var cooldown = cooldowns.First();

            if (Convert.ToDecimal(cooldown.CooldownTime) > Convert.ToDecimal(time))
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]User {user.Username} already in cooldown.");
                return(new JsonResult(ExceptionWorker.TooManyTryTimes())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }
            else
            {
                if (cooldown.TryTimes >= Program.SecurityLoginTryTimes)
                {
                    cooldown.CooldownLevel++;
                    cooldown.CooldownTime = time + cooldown.CooldownLevel * cooldown.CooldownLevel * 5 * 60;
                    db.SaveChanges();
                    log.Info($"[ID: {HttpContext.Connection.Id}]User {user.Username} got into cooldown.");
                    return(new JsonResult(ExceptionWorker.TooManyTryTimes())
                    {
                        StatusCode = (int)HttpStatusCode.Forbidden
                    });
                }
                cooldown.LastTryTime = time;
                cooldown.TryTimes++;
                db.SaveChanges();
            }

            // Password check.
            var salt           = user.CreateTime;
            var passwordHashed = HashWorker.HashPassword(request.password, salt);

            if (user.Password != passwordHashed)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]IP address {HttpContext.Connection.RemoteIpAddress}:{HttpContext.Connection.RemotePort} try to login with user {request.username} but wrong password.");
                return(new JsonResult(ExceptionWorker.InvalidPassword())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Update cooldown.
            cooldown.LastLoginTime = time;
            cooldown.TryTimes      = 0;
            db.SaveChanges();
            log.Info($"[ID: {HttpContext.Connection.Id}]Cooldown of user {request.username} has reseted.");

            // Hand token out and select profile.
            var accessToken = UuidWorker.GetUuid();
            var clientToken = string.Empty;

            if (request.clientToken != null)
            {
                clientToken = request.clientToken;
            }
            else
            {
                clientToken = UuidWorker.GetUuid();
            }

            Tokens token = new Tokens()
            {
                AccessToken = accessToken,
                ClientToken = clientToken,
                CreateTime  = time,
                Status      = 2
            };

            PostAuthrnticateResponse response = new PostAuthrnticateResponse();
            var profiles = from p in db.Profiles where p.Uid == user.Id select p;

            List <Profile> availableProfiles = new List <Profile>();

            foreach (var p in profiles)
            {
                var playerProfile = new Profile();
                playerProfile.id   = p.Uuid;
                playerProfile.name = p.Name;

                if (profiles.Count() > 1)
                {
                    if (p.IsSelected == 1)
                    {
                        response.selectedProfile = playerProfile;
                        token.BindProfileId      = p.Id;
                        log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} has logged and binded profile {playerProfile.name}.");
                    }
                }
                else if (profiles.Count() == 1)
                {
                    response.selectedProfile = playerProfile;
                    token.BindProfileId      = p.Id;
                    p.IsSelected             = 1;
                    log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} has logged and binded profile {playerProfile.name}.");
                }
                else
                {
                    log.Info($"[ID: {HttpContext.Connection.Id}]User {request.username} has logged but not bind any profile.");
                }

                availableProfiles.Add(playerProfile);
            }


            var tokens = from t in db.Tokens where t.BindProfileId == token.BindProfileId select t;

            foreach (var t in tokens)
            {
                t.Status = 1;
            }
            db.Tokens.Add(token);
            db.SaveChanges();

            // Build response
            response.accessToken = accessToken;
            response.clientToken = clientToken;

            var availableProfilesFinal = availableProfiles.ToArray();

            response.availableProfiles = availableProfilesFinal;

            if (request.requestUser)
            {
                var properties = new Properties()
                {
                    name  = "preferredLanguage",
                    value = user.PreferredLanguage
                };
                response.user = new User()
                {
                    id         = user.Username,
                    properties = new Properties[] { properties }
                };
            }
            return(new JsonResult(response));
        }
コード例 #8
0
        public JsonResult Refresh([FromBody] PostRefreshRequest request)
        {
            log.Info($"[ID: {HttpContext.Connection.Id}]{HttpContext.Connection.RemoteIpAddress.MapToIPv4()}:{HttpContext.Connection.RemotePort} tried to refresh token.");
            var isAlreadyBindProfile = false;

            // Check token.
            IQueryable <Tokens> tokens = null;

            if (request.clientToken != null)
            {
                tokens = from t in db.Tokens where t.AccessToken == request.accessToken && t.ClientToken == request.clientToken && t.Status >= 1 select t;
            }
            else
            {
                tokens = from t in db.Tokens where t.AccessToken == request.accessToken && t.Status >= 1 select t;
            }

            if (tokens.Count() != 1)
            {
                log.Info($"[ID: {HttpContext.Connection.Id}]Token invalid.");
                return(new JsonResult(ExceptionWorker.InvalidToken())
                {
                    StatusCode = (int)HttpStatusCode.Forbidden
                });
            }

            // Invalid token.
            int?profileId = null;
            int?userId    = null;
            var token     = tokens.First();

            if (token.BindProfileId != null)
            {
                profileId            = token.BindProfileId;
                isAlreadyBindProfile = true;
            }
            else
            {
                var profiles = from p in db.Profiles where p.Id == profileId select p;
                if (profiles.Count() == 1)
                {
                    userId = profiles.First().Uid;
                }
            }
            token.Status = 0;
            db.SaveChanges();
            log.Info($"[ID: {HttpContext.Connection.Id}]Access token {token.AccessToken} has invalided.");

            // Check others temp invalid tokens.
            var time = long.Parse(TimeWorker.GetTimeStamp10());
            var tempInvalidTokens = from t in db.Tokens where (long.Parse(t.CreateTime) + Program.TokensExpireDaysLimit * 24 * 60 * 60) <= time select t;

            foreach (var t in tempInvalidTokens)
            {
                t.Status = 1;
            }
            db.SaveChanges();

            // Delete invalid tokens.
            var invalidTokens = from t in db.Tokens where t.Status == 0 select t;

            foreach (var t in invalidTokens)
            {
                db.Tokens.Remove(t);
            }
            db.SaveChanges();

            // Bind profile.
            PostRefreshResponse response = new PostRefreshResponse();

            Tokens tokenNew = new Tokens();

            if (request.selectedProfile != null)
            {
                if (isAlreadyBindProfile)
                {
                    return(new JsonResult(ExceptionWorker.AlreadyBind())
                    {
                        StatusCode = (int)HttpStatusCode.Forbidden
                    });
                }
                else
                {
                    var profiles = from p in db.Profiles where p.Uuid == request.selectedProfile.Value.id select p;
                    var profile  = profiles.First();
                    if (profiles.Count() == 1)
                    {
                        profile.IsSelected       = 1;
                        profileId                = profile.Id;
                        tokenNew.BindProfileId   = profile.Id;
                        response.selectedProfile = request.selectedProfile;
                    }
                    ;
                    userId   = profile.Uid;
                    profiles = from p in db.Profiles where p.Uid == profile.Uid select p;
                    foreach (var p in profiles)
                    {
                        if (p.Id != profileId && p.IsSelected == 1)
                        {
                            p.IsSelected = 0;
                        }
                    }
                    db.SaveChanges();
                    log.Info($"[ID: {HttpContext.Connection.Id}]Bind profile {profile.Name}.");
                }
            }

            // Check if token reach the limit.
            tokens = from t in db.Tokens where t.BindProfileId == profileId && t.Status == 1 select t;
            if (tokens.Count() > Program.MaxTokensPerProfile)
            {
                long createTime = long.MaxValue;
                foreach (var t in tokens)
                {
                    if (long.Parse(t.CreateTime) <= createTime)
                    {
                        createTime = long.Parse(t.CreateTime);
                    }
                }
                tokens = from t in db.Tokens where t.BindProfileId == profileId && t.CreateTime == createTime.ToString() select t;
                tokens.First().Status = 0;
                db.SaveChanges();
            }

            // Build response and hand the new token out.
            response.accessToken = tokenNew.AccessToken = UuidWorker.GetUuid();
            if (request.clientToken != null)
            {
                response.clientToken = tokenNew.ClientToken = request.clientToken;
            }
            else
            {
                response.clientToken = tokenNew.ClientToken = UuidWorker.GetUuid();
            }
            tokenNew.CreateTime = time.ToString();
            tokenNew.Status     = 2;
            db.Tokens.Add(tokenNew);
            db.SaveChanges();

            // User info.
            if (request.selectedProfile == null && request.requestUser)
            {
                var users = from u in db.Users where u.Id == userId select u;
                var user  = users.First();

                var properties = new Properties()
                {
                    name  = "preferredLanguage",
                    value = user.PreferredLanguage
                };
                response.user = new User()
                {
                    id = user.Username
                };
            }

            return(new JsonResult(response));
        }