コード例 #1
0
        public async Task <AuthUserOutputModel> AuthenticateUser(AuthUserInputModel authUser)
        {
            try
            {
                var tokenDetails = new AuthUserOutputModel();
                var result       = await userRepository.GetByCondition(item => item.LoginName == authUser.LoginName && item.Password == authUser.Password);

                var user = new User();
                foreach (var item in result)
                {
                    user = item;
                }

                if (user.LoginName != null)
                {
                    tokenDetails       = mapper.Map <AuthUserOutputModel>(user);
                    tokenDetails.Token = AuthModule.GenerateToken(tokenDetails);
                }
                return(tokenDetails);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #2
0
        private static void RunProgram(DbDataSource dataSource)
        {
            while (true)
            {
                var authModule = new AuthModule(dataSource);

                var authResult = authModule.SignIn();

                switch (authResult.Role)
                {
                case RoleType.Client:
                {
                    var clientModule = new ClientModule(authResult.CurrentUserId, dataSource);
                    clientModule.WorkAsClient();

                    break;
                }

                case RoleType.Admin:
                {
                    var adminModule = new AdminModule(authResult.CurrentUserId, dataSource);
                    adminModule.WorkAsAdmin();

                    break;
                }

                default:
                {
                    throw new InvalidDataException();
                }
                }
            }
        }
コード例 #3
0
        public void AuthModule_Run_ExecutesFine()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                AuthModule authModule = new AuthModule();
                ShimHttpApplication.AllInstances.ContextGet = (a) =>
                {
                    return(new ShimHttpContext()
                    {
                        ItemsGet = () =>
                        {
                            return new Dictionary <object, object>();
                        }
                    });
                };
                ShimHttpContext.CurrentGet = () =>
                {
                    return(new ShimHttpContext());
                };
                ShimHttpContext.AllInstances.ResponseGet = (a) =>
                {
                    return(new ShimHttpResponse()
                    {
                        StatusCodeGet = () => { return 200; }
                    });
                };

                // Act
                authModule.Run(new HttpApplication(), new EventArgs());

                // Assert
                HttpContext.Current.Response.StatusCode.ShouldBe(200);
            }
        }
コード例 #4
0
ファイル: HttpServer.cs プロジェクト: RainsSoft/HttpWebServer
        /// <summary>
        /// Will request authentication.
        /// </summary>
        /// <remarks>
        /// Sends respond to client, nothing else can be done with the response after this.
        /// </remarks>
        /// <param name="mod"></param>
        /// <param name="request"></param>
        /// <param name="response"></param>
        protected virtual void RequestAuthentication(AuthModule mod, IHttpRequest request, IHttpResponse response)
        {
            string theResponse = mod.CreateResponse(GetRealm(request));

            response.AddHeader("www-authenticate", theResponse);
            response.Reason = "Authentication required.";
            response.Status = HttpStatusCode.Unauthorized;
        }
コード例 #5
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="authModule"></param>
 /// <param name="fileModule"></param>
 /// <param name="cacheModule"></param>
 /// <param name="thumbnailModule"></param>
 /// <param name="loggerFactory"></param>
 public UploadController(AuthModule authModule, FileModule fileModule, CacheModule cacheModule, ThumbnailModule thumbnailModule, ILoggerFactory loggerFactory)
 {
     this.authModule      = authModule;
     this.fileModule      = fileModule;
     this.cacheModule     = cacheModule;
     this.thumbnailModule = thumbnailModule;
     this.logger          = loggerFactory.CreateLogger("File");
 }
コード例 #6
0
        protected override AjaxResult ProcessRequestInternal(HttpContext context)
        {
            var login = AuthModule.GetAuthLogin();

            AntiFlood.CheckFlood($"{context.Request.CurrentExecutionFilePath}:{login}");

            var flags = DbStorage.FindFlags(login);

            if (ElCapitan.GameEnded(flags))
            {
                throw new HttpException(403, "The End");
            }

            var user = DbStorage.FindUserByLogin(login);

            if (user == null)
            {
                throw new HttpException(403, "Access denied");
            }

            if (user.EndTime != DateTime.MinValue && user.EndTime < DateTime.UtcNow)
            {
                throw new HttpException(403, "The End");
            }

            var question = context.Request.Form["question"].TrimToNull();

            if (question == null)
            {
                throw new HttpException(400, "Message is empty");
            }

            if (question.Length > Settings.MaxMsgLength)
            {
                throw new HttpException(400, "Message too large");
            }

            Flag flag;

            File[]   files;
            DateTime timer;

            var answer = ElCapitan.GetAnswer(question, flags, out flag, out files, out timer);
            var msg    = new Msg {
                Text = answer, Time = DateTime.UtcNow, Type = MsgType.Answer
            };

            DbStorage.AddDialog(login, new Msg {
                Text = question, Time = DateTime.UtcNow, Type = MsgType.Question
            }, new[] { msg }, flag, files);

            return(new AjaxResult {
                Messages = new[] { msg }, Files = files, Score = flag != null ? 1 : 0, Timer = timer == DateTime.MinValue ? DateTime.MinValue : (user.EndTime != DateTime.MinValue ? user.EndTime : timer)
            });
        }
コード例 #7
0
ファイル: Skype4Sharp.cs プロジェクト: VB6Hobbyst7/Skype3D
 public Skype4Sharp(Tokens tokens)
 {
     authTokens        = tokens;
     mainCookies       = new CookieContainer();
     mainFactory       = new HttpRequestFactory();
     mainPoll          = new Poller(this);
     selfProfile       = new User(this);
     mainUserModule    = new UserModule(this);
     mainAuthModule    = new AuthModule(this);
     mainMessageModule = new MessageModule(this);
     mainContactModule = new ContactModule(this);
 }
コード例 #8
0
 public Skype4Sharp(SkypeCredentials loginData, WebProxy loginProxy = null)
 {
     authInfo          = loginData;
     mainProxy         = loginProxy;
     mainFactory       = new WebRequestFactory(mainProxy, new CookieContainer());
     mainPoll          = new Poller(this);
     selfProfile       = new User(this);
     mainUserModule    = new UserModule(this);
     mainAuthModule    = new AuthModule(this);
     mainMessageModule = new MessageModule(this);
     mainContactModule = new ContactModule(this);
 }
コード例 #9
0
ファイル: Skype4Sharp.cs プロジェクト: VB6Hobbyst7/Skype3D
 public Skype4Sharp(SkypeCredentials loginData)
 {
     authInfo          = loginData;
     mainCookies       = new CookieContainer();
     mainFactory       = new HttpRequestFactory();
     mainPoll          = new Poller(this);
     selfProfile       = new User(this);
     mainUserModule    = new UserModule(this);
     mainAuthModule    = new AuthModule(this);
     mainMessageModule = new MessageModule(this);
     mainContactModule = new ContactModule(this);
 }
コード例 #10
0
        public ActionResult Valid(string userId, string passwd, string returnUrl)
        {
            if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(passwd))
            {
                return(RedirectToAction(nameof(Index), new { msg = "用户名和密码不能为空 !", userId = userId, passwd = passwd }));
            }

            using (var module = new AuthModule())
            {
                UserInfo user   = null;
                var      status = module.Signin(userId, passwd, out user);
                if (status == AccountLoginStatus.Success)
                {
                    CacheCurrentUser(user);
                    if (!string.IsNullOrWhiteSpace(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }

                    return(RedirectToAction("index", "admin"));
                }

                string msg = "登录失败 .";
                if (status == AccountLoginStatus.Error)
                {
                    msg = "发生错误 .";
                }

                if (status == AccountLoginStatus.ExceptionAccount)
                {
                    msg = "账户异常 .";
                }

                if (status == AccountLoginStatus.LockedAccount)
                {
                    msg = "账户已锁定 .";
                }

                if (status == AccountLoginStatus.PasswordError)
                {
                    msg = "密码错误 .";
                }

                if (status == AccountLoginStatus.UserNoExist)
                {
                    msg = "账户不存在 .";
                }

                return(RedirectToAction(nameof(Index), new { msg = msg, userId = userId, passwd = passwd, returnUrl = returnUrl }));
            }
        }
コード例 #11
0
    public override void Initialize(IServer server)
    {
        AuthModule     = server.GetModule <AuthModule>();
        RoomsModule    = server.GetModule <RoomsModule>();
        SpawnersModule = server.GetModule <SpawnersModule>();

        // Add game server handlers
        server.SetHandler(WorldDemoOpCodes.TeleportRequest, HandleTeleportRequest);

        // Add client handlers
        server.SetHandler(WorldDemoOpCodes.EnterWorldRequest, HandleEnterWorldRequest);
        server.SetHandler(WorldDemoOpCodes.GetCurrentZoneAccess, HandleGetZoneAccess);

        //----------------------------------------------
        // Spawn game servers (zones)

        // Find a spawner
        var spawner = SpawnersModule.GetSpawners().FirstOrDefault();

        if (spawner != null)
        {
            // We found a spawner we can use
            SpawnZoneServers(spawner);
        }
        else
        {
            // Spawners are not yet registered to the master,
            // so let's listen to an event and wait for them
            SpawnersModule.SpawnerRegistered += registeredSpawner =>
            {
                // Ignore if zones are already spawned
                if (_areZonesSpawned)
                {
                    return;
                }

                // Spawn the zones
                SpawnZoneServers(registeredSpawner);

                _areZonesSpawned = true;
            };
        }
    }
コード例 #12
0
        protected override void OnLoad(EventArgs e)
        {
            Login = AuthModule.GetAuthLogin();

            var msgs  = DbStorage.FindMessages(Login);
            var files = DbStorage.FindFiles(Login);

            if (msgs.Length == 0)
            {
                var answer = new Msg {
                    Text = ElCapitan.StartMessage, Time = DateTime.UtcNow, Type = MsgType.Answer
                };
                DbStorage.AddDialog(Login, null, new[] { answer }, null, files = ElCapitan.StartFiles);
                msgs = new[] { answer };
            }

            Chat.Messages  = msgs;
            Explorer.Files = files;

            var score = DbStorage.FindScores(Login).FirstOrDefault();

            if (score != null)
            {
                Avatar = score.Avatar;
                Stars  = score.Stars;
            }

            var flags = DbStorage.FindFlags(Login);

            HasBombTimer = ElCapitan.HasBombTimer(flags);

            var user = DbStorage.FindUserByLogin(Login);

            if (user == null)
            {
                throw new HttpException(403, "Access denied");
            }

            EndTime = user.EndTime != DateTime.MinValue ? user.EndTime : Settings.BombTimerEnd;

            StartBombTimer.Visible = HasBombTimer;
        }
コード例 #13
0
        public static RequestResponse Process(RawRequest rawRequest)
        {
            var requestType = RequestBuilder.GetRequestTypeFromRaw(rawRequest);

            switch (requestType)
            {
            case RequestTypes.Login:
                return(AuthModule.Login(
                           rawRequest.Data.SelectToken("login").Value <string>() ?? "",
                           rawRequest.Data.SelectToken("pass").Value <string>() ?? ""
                           ));

            case RequestTypes.LogOut:
                return(AuthModule.Logout(
                           rawRequest.Data.SelectToken("token").Value <string>() ?? ""
                           ));

            case RequestTypes.Register:
                return(AuthModule.Register(
                           rawRequest.Data.SelectToken("login").Value <string>() ?? "",
                           rawRequest.Data.SelectToken("pass").Value <string>() ?? "",
                           rawRequest.Data.SelectToken("email").Value <string>() ?? ""
                           ));
            }

            var token  = (string)rawRequest.Data["token"] ?? "";
            int userId = rawRequest.Data.Value <int?>("userId") ?? 0;

            var authMiddleware = AuthMiddleware.IsUserLoggedIn(
                token, userId
                );

            if (authMiddleware.Code != ReturnCodes.Success)
            {
                return(new RequestResponse(requestType, authMiddleware.Code));
            }

            // Next request requires auth

            return(null);
        }
コード例 #14
0
        protected override AjaxResult ProcessRequestInternal(HttpContext context)
        {
            var login = AuthModule.GetAuthLogin();

            AntiFlood.CheckFlood($"{context.Request.CurrentExecutionFilePath}:{login}");

            /*if(DateTime.UtcNow > Settings.BombTimerEnd)
             *      throw new HttpException(403, "Connection lost...");*/

            var user = DbStorage.FindUserByLogin(login);

            if (user == null)
            {
                throw new HttpException(403, "Access denied");
            }

            var revision = DbStorage.FindBroadcast(login);
            var flags    = DbStorage.FindFlags(login);

            var timer = ElCapitan.HasBombTimer(flags) ? (user.EndTime != DateTime.MinValue ? user.EndTime : Settings.BombTimerEnd) : DateTime.MinValue;

            var answers = ElCapitan.GetBroadcastMsgs(ref revision);

            if (answers.Length == 0)
            {
                return new AjaxResult {
                           Messages = null, Files = null, Score = 0, Timer = timer
                }
            }
            ;

            var msgs = answers.Select(msg => new Msg {
                Text = msg, Time = DateTime.UtcNow, Type = MsgType.Answer
            }).ToArray();

            DbStorage.AddDialog(login, null, msgs, null, null, revision);
            return(new AjaxResult {
                Messages = msgs, Files = null, Score = 0, Timer = timer
            });
        }
    }
コード例 #15
0
ファイル: HttpServer.cs プロジェクト: RainsSoft/HttpWebServer
        /// <summary>
        /// Handle authentication
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        /// <param name="session"></param>
        /// <returns>true if request can be handled; false if not.</returns>
        /// <exception cref="BadRequestException">Invalid authorization header</exception>
        protected virtual bool ProcessAuthentication(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            if (_authModules.Count > 0)
            {
                bool   authenticate = false;
                object authTag      = null;
                if (request.Headers["authorization"] != null)
                {
                    authenticate = true;
                    string authHeader = request.Headers["authorization"];
                    int    pos        = authHeader.IndexOf(' ');
                    if (pos == -1)
                    {
                        throw new BadRequestException("Invalid authorization header");
                    }
                    // first word identifies the type of authentication to use.
                    string word = authHeader.Substring(0, pos).ToLower();

                    // find the mod to use.
                    AuthModule mod = null;
                    lock (_authModules)
                    {
                        foreach (AuthModule aModule in _authModules)
                        {
                            if (aModule.Name != word)
                            {
                                continue;
                            }
                            mod = aModule;
                            break;
                        }
                    }
                    if (mod != null)
                    {
                        authTag = mod.Authenticate(authHeader, GetRealm(request), request.Method);
                        session[AuthModule.AuthenticationTag] = authTag;
                    }
                }


                // Check if auth is needed.
                if (authTag == null)
                {
                    lock (_authModules)
                    {
                        foreach (AuthModule module in _authModules)
                        {
                            if (!module.AuthenticationRequired(request))
                            {
                                continue;
                            }

                            RequestAuthentication(module, request, response);
                            return(false);
                        }

                        // modules can have inited the authentication
                        // and then the module.AuthenticationRequired method will not have been used.
                        if (authenticate && _authModules.Count > 0)
                        {
                            RequestAuthentication(_authModules[0], request, response);
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
コード例 #16
0
 public UserController(AuthModule pContext)
 {
     module = pContext;
 }
コード例 #17
0
        public void Constructor()
        {
            var module = new AuthModule();

            Assert.IsNotNull(module.Repository);
        }