/// <summary>
        /// Async register customer
        /// </summary>
        /// <param name="customer">Csutomer entity</param>
        /// <param name="password">Customer password</param>
        /// <returns>Registrated customer</returns>
        public async Task <Customers> Register(Customers customer, string password)
        {
            byte[] passwordHash;
            byte[] passwordSalt;
            AuthHelpers.CreatePasswordHash(password, out passwordHash, out passwordSalt);

            customer.CustomerPassword = passwordHash;
            customer.CustomerSalt     = passwordSalt;

            using (var transaction = _surveyOnlineContext.Database.BeginTransaction())
            {
                try
                {
                    await _surveyOnlineContext.AddAsync(customer);

                    await _surveyOnlineContext.SaveChangesAsync();

                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                }
            }
            return(customer);
        }
Example #2
0
    public static async void EnterMap(int fromClient, Packet packet)
    {
        AuthCore core = (AuthCore)Server.the_core;
        int      cid  = packet.ReadInt();
        int      sid  = packet.ReadInt();
        int      pid  = packet.ReadInt();

        if (!Security.Validate(cid, fromClient, sid))
        {
            return;
        }

        bool ownsPlayer = await AuthHelpers.AccountOwnsPlayer(cid, pid);

        if (!ownsPlayer)
        {
            core.Clients[fromClient].tcp.Disconnect();
            return;
        }

        DataTable result = await AuthHelpers.GetPlayerData(pid);

        await AuthHelpers.AssignPidToSession(result, cid);

        AuthHelpers.MakeClientConnectToGameServer(result, cid);
    }
Example #3
0
    public static async void Authenticate(int fromClient, Packet packet)
    {
        AuthCore core     = (AuthCore)Server.the_core;
        int      id       = packet.ReadInt();
        string   user     = packet.ReadString();
        string   password = packet.ReadString();

        if (!Security.ReceivedIdMatchesClientId(id, fromClient))
        {
            AuthHelpers.SendAuthFailed(fromClient);
            return;
        }

        int aid = await AuthHelpers.GetAidFromLoginPassword(fromClient, user, password);

        bool hasSession = await AuthHelpers.DoesAidHaveSession(aid);

        if (!hasSession)
        {
            AuthHelpers.SetSessionIDtoClient(fromClient, aid);
            core.Clients[fromClient].setAID(aid);
            AuthHelpers.CreateSessionInDatabase(fromClient, aid);
            CharacterSelectionEntry[] characters = await AuthHelpers.GetCharactersInAccount(aid);

            AuthHelpers.SendCharacterSelectionDataToClient(fromClient, characters);
        }
        else
        {
            core.Clients[fromClient].setAID(aid);
            AuthHelpers.SendAlreadyConnectedPacket(fromClient);
            AuthHelpers.SendDisconnectPacketToAlreadyConnectedClient(fromClient);
        }
    }
        public AuthenticationCodeController GetAuthenticationCodeController(CoreaccesscontrolContext context, IApiService apiService)
        {
            Logger.Init(GetAppSettings().ConnectionStrings.DefaultConnection, "CoreAccessControl.log", "CoreAccessControl", Severity.Information, mock: true);
            var authHelpers = new AuthHelpers(GetMockHttpContextAccessor().Object);
            var service     = new AuthenticationCodeService(context, new FakeEmailSender(), new FakeEmailService(), apiService);

            return(new AuthenticationCodeController(service, authHelpers));
        }
        public AccessHistoryController GetAccessHistoryController(CoreaccesscontrolContext context, IApiService apiService)
        {
            Logger.Init(GetAppSettings().ConnectionStrings.DefaultConnection, "CoreAccessControl.log", "CoreAccessControl", Severity.Information, mock: true);
            var authHelpers = new AuthHelpers(GetMockHttpContextAccessor().Object);
            var service     = new AccessHistoryService(apiService);

            return(new AccessHistoryController(service, authHelpers));
        }
        public KeyholderController GetKeyholderController(CoreaccesscontrolContext context, IApiService apiService)
        {
            Logger.Init("", "CoreAccessControl.log", "CoreAccessControl", Severity.Information, mock: true);
            var authHelpers = new AuthHelpers(GetMockHttpContextAccessor().Object);
            var service     = new KeyholderService(context, apiService);

            return(new KeyholderController(service, authHelpers));
        }
        public ActionResult Login()
        {
            if (AuthHelpers.IsAuthenticated(User))
            {
                return(RedirectAfterLogin(true));
            }

            return(View());
        }
Example #8
0
        public HDNHD.Models.DataContexts.Dangnhap CheckLogin(string loginToken, TimeSpan validSpan)
        {
            var validTime = DateTime.Now.Subtract(validSpan);
            var dangNhap  = GetSingle(m => m.Trangthaikhoa != true &&
                                      AuthHelpers.MD5(m.NguoidungID.ToString()) == loginToken &&
                                      m.Thoigiandangnhap > validTime);

            return(dangNhap);
        }
Example #9
0
        public async Task <IActionResult> RegisterUser([FromBody] UserRegistration userRegistration)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            string userDefaultLeagueCode = null;

            if (!userRegistration.DoNotSetDefaultLeague)
            {
                if (String.IsNullOrEmpty(userRegistration.DefaultLeagueCode))
                {
                    return(new BadRequestObjectResult($"Setting default league, but none passed in"));
                }
                else
                {
                    userDefaultLeagueCode = userRegistration.DefaultLeagueCode;
                    var league = await this._leagueService.ReadLeague(userDefaultLeagueCode);

                    // this verifies the exact league casing
                    userDefaultLeagueCode = league.LeagueCode;
                }
            }

            var newPickEmUser = new PickEmUser
            {
                Email             = userRegistration.Email,
                UserName          = userRegistration.UserName,
                DefaultLeagueCode = userDefaultLeagueCode
            };

            var result = await _userManager.CreateAsync(newPickEmUser, userRegistration.Password);

            if (!result.Succeeded)
            {
                return(new BadRequestObjectResult(AuthHelpers.AddErrorsToModelState(result, ModelState)));
            }

            if (!userRegistration.DoNotSetDefaultLeague)
            {
                await _leagueService.AddLeaguePlayer(userDefaultLeagueCode, new LeaguePlayerAdd { PlayerTag = userRegistration.UserName, UserName = userRegistration.UserName });
            }

            string resultMessage = string.Format("User ({0}) created", userRegistration.UserName);

            _logger.LogInformation(resultMessage);

            User newUser = new User
            {
                DefaultLeagueCode = userDefaultLeagueCode,
                Email             = userRegistration.Email,
                UserName          = userRegistration.UserName
            };

            return(new OkObjectResult(newUser));
        }
Example #10
0
        public AutoMapping()
        {
            CreateMap <User, UserViewModel>().BeforeMap((a, b) => a.Password = null);

            //no mapeamento automaticamente converte a string de senha para hash
            CreateMap <UserViewModel, User>().BeforeMap((a, b) => a.Password = AuthHelpers.getHashOfString(a.Password));

            CreateMap <UserAuthViewModel, User>().BeforeMap((a, b) => a.Password = AuthHelpers.getHashOfString(a.Password));
        }
        public async Task AuthorizeAndGetToken()
        {
            // Only useful for local machine testing
            var username = "******";
            var password = "******";

            var jwt = await AuthHelpers.CreateAuthorize(username, password);

            Assert.IsTrue(!string.IsNullOrWhiteSpace(jwt.Token));
        }
Example #12
0
        public ActionResult Login(string returnUrl)
        {
            if (_apiConfig.IsProduction)
            {
                var url = AuthHelpers.GetSpareBank1AuthorizeUrl(_apiConfig.ClientId, _apiConfig.RedirectUri, returnUrl);
                return(Redirect(url));
            }

            RequestDevelopmentToken();
            return(Redirect(returnUrl));
        }
Example #13
0
        public void can_hash_twice_same_string()
        {
            // Arrange
            var password  = "******";
            var password2 = "WenderPatrick1122$";

            // Act
            var hash = AuthHelpers.getHashOfString(password);

            //Assert
            Assert.Equal(AuthHelpers.getHashOfString(password2), hash);
        }
Example #14
0
        public void different_string_has_diferrent_hash()
        {
            //Arrange
            var password  = "******";
            var password2 = "wenderpatrick1122$";

            //act
            var hash = AuthHelpers.getHashOfString(password);

            //assert
            Assert.NotEqual(AuthHelpers.getHashOfString(password2), hash);
        }
        public async Task CanAddUpdateAndDeleteEntries()
        {
            try
            {
                var session = await GetAuth().MockAuthenticationAsync(Credentials.Random);

                Assert.IsTrue(session.HasValue);
                Assert.IsNotNull(session.Value);

                var networkOperations = new Network.NetworkDataOps(session.Value);
                var md = await networkOperations.CreateEmptyMd(DataProtocol.DEFAULT_PROTOCOL);

                var mdOps = new Network.MdDataOps(session.Value, md);
                await mdOps.AddObjectAsync(AuthHelpers.GetRandomString(10), AuthHelpers.GetRandomString(10));

                var entries = await mdOps.GetEntriesAsync();

                Assert.AreEqual(1, entries.Count);

                var key = AuthHelpers.GetRandomString(10);
                await mdOps.AddObjectAsync(key, AuthHelpers.GetRandomString(10));

                entries = await mdOps.GetEntriesAsync();

                Assert.AreEqual(2, entries.Count);

                var newValue = AuthHelpers.GetRandomString(10);
                await mdOps.UpdateObjectAsync(key, newValue, 0);

                entries = await mdOps.GetEntriesAsync();

                var fetchedValue = entries
                                   .Where(e => e.Key.Key.ToUtfString() == key)
                                   .FirstOrDefault().Value.Content
                                   .ToUtfString()
                                   .Parse <string>();

                Assert.AreEqual(
                    newValue,
                    fetchedValue);

                await mdOps.DeleteObjectAsync(key, 1);

                entries = await mdOps.GetEntriesAsync();

                Assert.AreEqual(1, entries.Count);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
        public ActionResult Login(LoginForm form)
        {
            if (AuthHelpers.IsAuthenticated(User))
            {
                return(RedirectAfterLogin(true));
            }

            if (!ModelState.IsValid)
            {
                // Something went wrong during binding probably
                return(View());
            }

            string             username = TimetableUserEntry.NormalizeUsernameToId(form.Username);
            TimetableUserEntry user     = new TimetableUserRepository().GetByUsername(username);

            if (user == null)
            {
                ModelState.AddModelError("Username", "This username doesn't exist");
                return(View());
            }

            // https://stackoverflow.com/a/31585768/2588539
            ClaimsIdentity identity = new ClaimsIdentity(
                new[]
            {
                // These 2 are required for default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, username),
                new Claim(
                    "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                    "ASP.NET Identity",
                    "http://www.w3.org/2001/XMLSchema#string"
                    ),

                // Additional stuff
                new Claim(ClaimTypes.Role, user.IsStudentSupport ? Roles.StudentSupport : Roles.Student),
                new Claim(ClaimTypes.Name, user.Fullname),
                new Claim(AuthHelpers.DebugModeClaim, "1")
            },
                DefaultAuthenticationTypes.ApplicationCookie
                );

            HttpContext.GetOwinContext().Authentication.SignIn(
                new AuthenticationProperties {
                IsPersistent = false
            },
                identity
                );

            return(RedirectAfterLogin());
        }
Example #17
0
        public DormitoryController(
            IDormitoryRepository dormitoryRepository, IUserRepository userRepository,
            IRoomRepository roomRepository, UserManager <ApplicationUser> userManager,
            IAuthorizationService authorizationService, IAnnouncementRepository announcementRepo,
            IStringLocalizer <LangResources> localizer)
        {
            _dormitoryRepo    = dormitoryRepository;
            _userRepo         = userRepository;
            _roomRepo         = roomRepository;
            _userManager      = userManager;
            _announcementRepo = announcementRepo;
            _localizer        = localizer;

            _authHelpers = new AuthHelpers(authorizationService, _dormitoryRepo);
        }
        public LaundryController(
            ILaundryRepository laundryRepository, IReservationRepository reservationRepository,
            IUserRepository userRepository, IWashingMachineRepository washingMachineRepo,
            UserManager <ApplicationUser> userManager, IAuthorizationService authorizationService,
            IDormitoryRepository dormitoryRepository, IStringLocalizer <LangResources> localizer)
        {
            _laundryRepo        = laundryRepository;
            _reservationRepo    = reservationRepository;
            _userRepo           = userRepository;
            _userManager        = userManager;
            _washingMachineRepo = washingMachineRepo;
            _dormitoryRepo      = dormitoryRepository;
            _localizer          = localizer;

            _authHelpers = new AuthHelpers(authorizationService, dormitoryRepository);
        }
Example #19
0
        private void RequestTokenAndSignIn(IDictionary <string, object> parameters)
        {
            parameters.Add("client_id", _apiConfig.ClientId);
            parameters.Add("client_secret", _apiConfig.ClientSecret);

            var client  = new RestClient(_apiConfig.BaseUrl + "oauth/token");
            var request = new RestRequest(Method.POST);

            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddParameter("application/x-www-form-urlencoded", AuthHelpers.CreateQueryString(parameters), ParameterType.RequestBody);
            var response   = client.Execute(request);
            var oAuthToken = JsonSerializer.Deserialize <OAuthTokenResponse>(response.Content);

            SignIn(oAuthToken.access_token);
        }
        /// <summary>
        /// Async login customer
        /// </summary>
        /// <param name="customerName">Input customer name</param>
        /// <param name="password">Input customer password</param>
        /// <returns>Loginned customer</returns>
        public async Task <Customers> Login(string customerName, string password)
        {
            var customer = await _surveyOnlineContext.Customers.FirstOrDefaultAsync(c => c.CustomerName == customerName);

            if (customer == null)
            {
                return(null);
            }

            if (!AuthHelpers.VerifyPassword(password, customer.CustomerPassword, customer.CustomerSalt))
            {
                return(null);
            }

            return(customer);
        }
Example #21
0
    public static async void SendTargetGameServerForWarp(int fromClient, Packet packet)
    {
        AuthCore core = (AuthCore)Server.the_core;
        int      cid  = packet.ReadInt();
        int      sid  = packet.ReadInt();
        int      pid  = packet.ReadInt();
        int      map  = packet.ReadInt();

        if (!Security.ReceivedIdMatchesClientId(cid, fromClient))
        {
            AuthHelpers.SendAuthFailed(fromClient);
            return;
        }

        List <MySqlParameter> _params = new List <MySqlParameter>()
        {
            MySQL_Param.Parameter("?session", sid),
            MySQL_Param.Parameter("?pid", pid),
        };
        DataTable rows = await Server.DB.QueryAsync("SELECT COUNT(*) AS count FROM [[player]].sessions WHERE `session`=?session AND `pid`=?pid LIMIT 1", _params);

        if (Int32.Parse(rows.Rows[0]["count"].ToString()) > 0)
        {
            DataTable result = await AuthHelpers.GetPlayerData(pid);

            List <MySqlParameter> mapParams = new List <MySqlParameter>()
            {
                MySQL_Param.Parameter("?map", map),
                MySQL_Param.Parameter("?x", Config.SpawnPositionsForMaps[map].X),
                MySQL_Param.Parameter("?y", Config.SpawnPositionsForMaps[map].Y),
                MySQL_Param.Parameter("?z", Config.SpawnPositionsForMaps[map].Z),
                MySQL_Param.Parameter("?pid", pid),
            };
            await Server.DB.QueryAsync("UPDATE [[player]].player SET `map`=?map, `x`=?x, `y`=?y, `z`=?z WHERE `id`=?pid LIMIT 1", mapParams);

            ((AuthCore)Server.the_core).Clients[cid].session_id = sid;
            AuthHelpers.MakeClientConnectToGameServer(result, cid, map);
        }
        else
        {
            Logger.Syserr($"Player #{pid} attempted to enter map #{map} but the session missmatched (sid of {sid})");
            // todo : send a disconnect packet to the client
        }
    }
Example #22
0
        /// <summary>
        /// create admin account if no account exists
        /// </summary>
        public ActionResult Seed()
        {
            int count = nguoiDungRepository.GetAll().Count();

            if (count == 0)
            {
                var password = AuthHelpers.CreatePassword("123456");

                adminUow.BeginTransaction();
                try
                {
                    var nguoiDung = new HDNHD.Models.DataContexts.Nguoidung()
                    {
                        Taikhoan = "admin",
                        Isadmin  = true,
                        Matkhau  = password
                    };
                    nguoiDungRepository.Insert(nguoiDung);
                    adminUow.SubmitChanges();

                    var dangNhap = new HDNHD.Models.DataContexts.Dangnhap()
                    {
                        NguoidungID      = nguoiDung.NguoidungID,
                        Solandangnhapsai = 0
                    };
                    dangNhapRepository.Insert(dangNhap);

                    adminUow.SubmitChanges();
                    adminUow.Commit();

                    return(Content("Created user: '******' successfully!"));
                }
                catch (Exception e)
                {
                    adminUow.RollBack();
                    return(Content("Fail to create seeding user: '******'."));
                }
            }

            return(Content("Users exist. Seeding aborted!"));
        }
Example #23
0
        public async Task <IActionResult> AcceptPhone([FromBody] AcceptPhoneDTO acceptPhoneDTO)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }

                ResponseDTO answer = await userAuthService.CheckUser(acceptPhoneDTO.PhoneNumber);

                if (answer.Status == false)
                {
                    return(Ok(new { answer }));
                }

                string verificationCode = AuthHelpers.RandomString(6);
                answer = await smsService.SendVerificationCode(acceptPhoneDTO.PhoneNumber, verificationCode);

                if (answer.Status == false)
                {
                    return(StatusCode(500, answer));
                }

                return(Ok(new { answer }));
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                return(StatusCode(500, new ResponseDTO()
                {
                    Message = "На данный момент на стороне сервера ошибка, пожалуйста повторите попытку позже",
                    Status = false
                }));
            }
        }
 public KeyholderController(IKeyholderService keyholderService, AuthHelpers authHelpers)
 {
     _keyHolderService = keyholderService;
     _authHelpers      = authHelpers;
 }
Example #25
0
 public AdminController(IAdminService adminService, AuthHelpers authHelpers, IAuthService authService)
 {
     _adminService = adminService;
     _authHelpers  = authHelpers;
     _authService  = authService;
 }
        public ActionResult LoginSso(string timetableToken, string returnUrl)
        {
            if (AuthHelpers.IsAuthenticated(User))
            {
                return(RedirectAfterLogin(true));
            }

            if (timetableToken == null)
            {
                // Store the return URL in session to use it when the user comes back
                if (!string.IsNullOrWhiteSpace(returnUrl))
                {
                    Session[ReturnUrlKey] = returnUrl;
                }

                return(RedirectToSso());
            }

            if (!Guid.TryParse(timetableToken, out Guid tokenGuid))
            {
                AuthHelpers.Logger.Information(
                    "SSO Fail: failed to parse token GUID '{token}' from {UserHostAddress} ",
                    timetableToken, Request.UserHostAddress
                    );

                return(FailCallback());
            }

            TimetableDbContext timetableDb = new TimetableDbContext();
            AuthToken          token       = timetableDb.AuthTokens.Find(tokenGuid);

            if (token == null || token.UserHostAddress != Request.UserHostAddress)
            {
                AuthHelpers.Logger.Information(
                    "SSO Fail: Token {Guid} not found or UserHostAddress ({UserHostAddress}) doesn't match",
                    tokenGuid, Request.UserHostAddress
                    );

                return(FailCallback());
            }

            AuthSession session = timetableDb.AuthSessions.Find(token.SessionGuid);

            if (session == null || session.ExpiresAt < DateTime.Now)
            {
                AuthHelpers.Logger.Information(
                    "SSO Fail: Session for token {Guid} not found or it has expired. UserHostAddress: {UserHostAddress}",
                    tokenGuid, Request.UserHostAddress
                    );

                return(FailCallback());
            }

            TimetableUserEntry user = new TimetableUserRepository(timetableDb)
                                      .GetByUsername(session.UserEmail);

            if (user == null || user.UserId != TimetableUserEntry.NormalizeUsernameToId(session.UserEmail))
            {
                AuthHelpers.Logger.Information(
                    "SSO Fail: Session for token {Guid} failed to match a timetable user. UserHostAddress: {UserHostAddress}",
                    tokenGuid, Request.UserHostAddress
                    );

                return(FailCallback());
            }

            // All good, sign in

            timetableDb.AuthTokens.Remove(token);
            timetableDb.SaveChanges();

            ClaimsIdentity identity = new ClaimsIdentity(
                new[]
            {
                // These 2 are required for default antiforgery provider
                new Claim(ClaimTypes.NameIdentifier, user.UserId),
                new Claim(
                    "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
                    "ASP.NET Identity",
                    "http://www.w3.org/2001/XMLSchema#string"
                    ),

                // Additional stuff
                new Claim(ClaimTypes.Role, user.IsStudentSupport ? Roles.StudentSupport : Roles.Student),
                new Claim(ClaimTypes.Name, user.Fullname),
                new Claim(AuthHelpers.TimetableSessionClaim, session.Guid.ToString())
            },
                DefaultAuthenticationTypes.ApplicationCookie
                );

            Session[FailedSsoAttemptsKey] = 0;
            HttpContext.GetOwinContext().Authentication.SignIn(
                new AuthenticationProperties
            {
                IsPersistent = true     // We validate on every request anyway, so prevent needless redirects
            },
                identity
                );

            AuthHelpers.Logger.Information(
                "SSO Success: token {Guid} was used for successful sign in by {UserId}. UserHostAddress: {UserHostAddress}",
                tokenGuid, user.UserId, Request.UserHostAddress
                );

            return(RedirectAfterLogin());
        }
 public AuthController(IAuthService authService, AuthHelpers authHelpers)
 {
     _authService = authService;
     _authHelpers = authHelpers;
 }
Example #28
0
 private bool RefreshTime(long refreshTime)
 {
     return(AuthHelpers.GetUnixTime(DateTime.Now) > refreshTime);
 }
 public AuthenticationCodeController(IAuthenticationCodeService authenticationCodeService, AuthHelpers authHelpers)
 {
     _authenticationCodeService = authenticationCodeService;
     _authHelpers = authHelpers;
 }
 public ConfigController(IConfigService configService, AuthHelpers authHelpers)
 {
     _configService = configService;
     _authHelpers   = authHelpers;
 }