コード例 #1
0
        private void button_Click(object sender, EventArgs e)
        {
            MainForm.ID_NOTE = Convert.ToInt32((sender as Button).Tag.ToString());
            DataTable dt = new DataTable();

            dt = noteController.GetDataWithID(MainForm.ID_USER, MainForm.ID_NOTE);

            foreach (DataRow dr in dt.Rows)
            {
                if (dr["PASSWORD"].ToString() == "" || dr["PASSWORD"].ToString().Length == 0)
                {
                    CreateNote cn = new CreateNote();
                    this.Controls.Add(cn);
                    cn.Dock = DockStyle.Fill;
                    cn.BringToFront();
                }
                else
                {
                    AuthForm auth = new AuthForm();
                    auth.ShowDialog();

                    if (AuthForm.checkPass)
                    {
                        CreateNote cn = new CreateNote();
                        this.Controls.Add(cn);
                        cn.Dock = DockStyle.Fill;
                        cn.BringToFront();
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
コード例 #2
0
        public void EnsureAuthenticated()
        {
            var computerInfo = _computerInfoService.GetComputerInfo();

            if (computerInfo.PersistentData.SessionId != null && computerInfo.PersistentData.SecretKey != null)
            {
                // Check if the existing session is still valid.
                var authInfo = _jamHostApiService.ValidateSession();
                if (authInfo.IsValid)
                {
                    // Already authenticated.
                    _userInfo.Authenticated = true;
                    _userInfo.FullName      = authInfo.FullName;
                    _userInfo.Email         = authInfo.EmailAddress;
                    _userInfo.AccountType   = authInfo.AccountType;
                    return;
                }
            }

            AuthForm way = new AuthForm(_siteInfo.GetSiteInfo(), _imageService, _jamHostApiService, _computerInfoService);

            if (way.ShowDialog() != DialogResult.OK)
            {
                Environment.Exit(1);
            }

            _userInfo.Authenticated = true;
            _userInfo.FullName      = way.AuthResult.FullName;
            _userInfo.Email         = way.AuthResult.EmailAddress;
            _userInfo.AccountType   = way.AuthResult.AccountType;

            way.Dispose();
            GC.Collect();
        }
コード例 #3
0
        private void button_Click(object sender, EventArgs e)
        {
            MainForm.ID_NOTE = Convert.ToInt32((sender as Button).Tag.ToString());
            DataTable dt = new DataTable();

            dt = noteController.GetDataWithID(MainForm.ID_USER, MainForm.ID_NOTE);

            foreach (DataRow dr in dt.Rows)
            {
                if (dr["PASSWORD"].ToString() == "" || dr["PASSWORD"].ToString().Length == 0)
                {
                    DisplayForm display = new DisplayForm();
                    display.ShowDialog();
                }
                else
                {
                    AuthForm auth = new AuthForm();
                    auth.ShowDialog();

                    if (AuthForm.checkPass)
                    {
                        DisplayForm display = new DisplayForm();
                        display.ShowDialog();
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
コード例 #4
0
        private string Auth(Socket handler)
        {
            AuthForm auth_data = AuthForm.FromBytes(ReadBytes(handler));

            if (Users.ContainsKey(auth_data.Login))
            {
                if (Users[auth_data.Login].Session == auth_data.Session)
                {
                    Users[auth_data.Login].MySocket = handler;
                    return(auth_data.Login);
                }
                else
                {
                    throw new Exception("Unknown user");
                }
            }
            else
            {
                Users[auth_data.Login] = new Info()
                {
                    MySocket = handler, Session = auth_data.Session
                };
                return(auth_data.Login);
            }
        }
コード例 #5
0
        private void AuthButton_Click(object sender, RoutedEventArgs e)
        {
            if (!IsFilled())
            {
                MessageBox.Show("Not all fields was filled");
                return;
            }
            IPAddress addr = IPAddress.Parse(ServerBox.Text);

            try
            {
                AuthForm authForm = null;
                if (SessionBox.Text.Length > 0)
                {
                    authForm = new AuthForm(LoginBox.Text, Convert.ToInt32(SessionBox.Text));
                }
                else
                {
                    authForm = new AuthForm(LoginBox.Text);
                }
                CoreClient.MessageClient messageClient = new CoreClient.MessageClient(addr, Convert.ToInt32(PortBox.Text), authForm);
                messageClient.Authorize();
                IsAuth = true;
                MessageWindow.Client     = messageClient;
                MessageWindow.Visibility = Visibility.Visible;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #6
0
 public MessageClient(IPAddress addr, int port, AuthForm auth)
 {
     Auth     = false;
     IPPoint  = new IPEndPoint(addr, port);
     authForm = auth;
     Items    = new ConcurrentQueue <Data>();
     MySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 }
コード例 #7
0
        public LoginPresenter(AuthForm form2, ILoginService loginService)
        {
            _form2        = form2;
            _loginService = loginService;


            _btnLogin        = _form2.login;
            _btnLogin.Click += Login_Click;
        }
コード例 #8
0
        public void ShowAuthForm()
        {
            if (this.authForm == null)
            {
                this.authForm = new AuthForm();
            }

            authForm.Show();
        }
コード例 #9
0
 private bool createForm(bool isAuth, Form form)
 {
     try
     {
         AuthForm aForm = new AuthForm(this, isAuth);
         aForm.ShowDialog(form);
         return(true);
     }
     catch
     { return(false); }
 }
コード例 #10
0
        private void ToolStripMenuItem_auth_Click(object sender, EventArgs e)
        {
            // login form
            AuthForm authform = new AuthForm();

            if (authform.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // verify user login
                authenticate(authform.id, authform.pass);
            }
        }
コード例 #11
0
        public IActionResult Authenticate([FromBody] AuthForm auth)
        {
            var user = _service.Authenticate(auth.Username, auth.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(Ok(user));
        }
コード例 #12
0
ファイル: StartupForm.cs プロジェクト: BesuglovS/nudata
        private void ShowAuthForm()
        {
            if (_authFormOpened)
            {
                AuthForm.Activate();
                AuthForm.Focus();
                return;
            }

            AuthForm        = new AuthForm(ApiEndpoint);
            _authFormOpened = true;
            AuthForm.Show();
            _authFormOpened = false;
        }
コード例 #13
0
        public MainForm()
        {
            AuthForm authForm = new AuthForm();

            authForm.ShowDialog();
            if (authForm.DialogResult == DialogResult.OK)
            {
                Account = authForm.Account;
                InitializeComponent();
                this.StartPosition = FormStartPosition.CenterScreen;
                Books = bookService.GetAll();
                lbBooksList.DataSource = Books;
            }
            else
            {
                this.Load += new EventHandler(CloseOnStart);
            }
        }
コード例 #14
0
        private void Form1_Load(object sender, EventArgs e)
        {
            AuthForm auth = new AuthForm();

            while (auth.ShowDialog() != DialogResult.OK)
            {
                if (MessageBox.Show("Credenciales Incorrectas", "No se pudo conectar a la base de datos", MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                {
                    this.Close();
                }
            }

            accordionControlElement1.Expanded = false;
            accordionControlElement7.Expanded = false;
            accordionControlElement2.Expanded = false;
            accordionControlElement5.Expanded = false;
            accordionControlElement6.Expanded = false;
        }
コード例 #15
0
        public IActionResult Register(AuthForm register)
        {
            _logger.LogInformation("Registration initiated");
            var user = _userService.Get(register.UserName);

            if (user != null)
            {
                _logger.LogWarning("Duplicate user {User} found", register.UserName);
                return(Conflict(new { message = @"Username already exists" }));
            }

            var salt = Auth.GenerateSalt();

            var argon2Config = new Argon2Config
            {
                Threads    = Environment.ProcessorCount,
                Password   = Encoding.UTF8.GetBytes(register.Password),
                Salt       = salt,
                HashLength = 128
            };
            var hashedPassword = Argon2.Hash(argon2Config);

            var accessToken  = Auth.GenerateJWToken(_config, register.UserName);
            var refreshToken = Auth.GenerateRefreshToken(_config, register.UserName);

            user = new User
            {
                UserName     = register.UserName,
                Password     = hashedPassword,
                Salt         = salt,
                AccessToken  = accessToken.Token,
                RefreshToken = refreshToken.Token,
                AccessExpiry = accessToken.Expiry
            };

            _ = _userService.Add(user);

            return(Ok(new
            {
                accessToken = accessToken.Token,
                refreshToken = refreshToken.Token
            }));
        }
コード例 #16
0
        public TaskResult Email2Token(AuthForm authForm)
        {
            if (String.IsNullOrEmpty(authForm.Email))
            {
                return(Error(401, "user email could not be empty!"));
            }
            if (String.IsNullOrEmpty(authForm.Password))
            {
                return(Error(401, "user password could not be empty!"));
            }

            var foundedAuthentication = DB.Authentications.FirstOrDefault(auth => auth.Type == Authentication.AuthenticationType.Email && auth.Identifier == authForm.Email);

            var passwordHasher = new PasswordHasher <Authentication>();

            var authentication = new Authentication()
            {
                Type       = Authentication.AuthenticationType.Email,
                Identifier = authForm.Email
            };

            if (foundedAuthentication == null)
            {
                authentication.Parameters = passwordHasher.HashPassword(authentication, authForm.Password);

                DB.Authentications.Add(authentication);
                DB.SaveChanges();

                return(Result(new { token = generateToken(authentication.Id, null) }, String.Format("user '{0}' created successfully", authForm.Email)));
            }
            else
            {
                var result = passwordHasher.VerifyHashedPassword(foundedAuthentication, foundedAuthentication.Parameters, authForm.Password);
                if (result == PasswordVerificationResult.Success)
                {
                    return(Result(new { token = generateToken(foundedAuthentication.Id, null) }, String.Format("user '{0}' logged in successfully", authForm.Email)));
                }
                else
                {
                    return(Error(401, String.Format("user's {0} password is incorrect!", authForm.Email)));
                }
            }
        }
コード例 #17
0
        public IActionResult Login(AuthForm login)
        {
            _logger.LogInformation("Login initiated");
            IActionResult response = Unauthorized();

            var user = _userService.Get(login.UserName);

            if (user == null)
            {
                _logger.LogWarning("User {User} not found", login.UserName);
                return(response);
            }

            var argon2Config = new Argon2Config
            {
                Threads    = Environment.ProcessorCount,
                Password   = Encoding.UTF8.GetBytes(login.Password),
                Salt       = user.Salt,
                HashLength = 128
            };

            if (Argon2.Verify(user.Password, argon2Config))
            {
                _logger.LogInformation("User {User} logged in", login.UserName);
                var accessToken  = Auth.GenerateJWToken(_config, user.UserName);
                var refreshToken = Auth.GenerateRefreshToken(_config, user.UserName);

                user.AccessToken  = accessToken.Token;
                user.RefreshToken = refreshToken.Token;
                user.AccessExpiry = accessToken.Expiry;

                _userService.Update(user.Id, user);

                return(Ok(new
                {
                    accessToken = accessToken.Token,
                    refreshToken = refreshToken.Token
                }));
            }

            _logger.LogWarning("User {User} provided wrong password", login.UserName);
            return(response);
        }
コード例 #18
0
ファイル: AuthController.cs プロジェクト: DAtink/jwt-auth
        public async Task Token(AuthForm form)
        {
            var username = form.Login;
            var password = form.Password;

            var identity = GetIdentity(username, password);

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

                return;
            }

            var now = DateTime.UtcNow;
            // создаем JWT-токен
            var jwt = new JwtSecurityToken(
                issuer: AuthOptions.ISSUER,
                audience: AuthOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                username     = identity.Name
            };

            // сериализация ответа
            Response.ContentType = "application/json";
            await Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
コード例 #19
0
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     try
     {
         var authForm = new AuthForm();
         if (authForm.ShowDialog() == DialogResult.OK)
         {
             if (authForm.Usr.GetType() == typeof(Admin))
             {
                 Application.Run(adminForm = new AdminWindowForm());
             }
             else
             {
                 Application.Run(new PlayerWindowForm((Player)authForm.Usr));
             }
         }
     }
     catch (Exception)
     {
         MessageBox.Show("Произошла ошибка в работе системы!", "Ошибка в работе", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
コード例 #20
0
        public bool ConnectToComputer()
        {
            if (m_Namespace != null && m_Namespace.IsConnected)
            {
                return(true);
            }
            string            connectionString = MakeConnectionString();
            ConnectionOptions options          = null;
            bool autoLogon = false;

TryAgainWithPassword:
            try
            {
                options = new ConnectionOptions();
                //options.Impersonation = true;
                m_Namespace = new ManagementScope(connectionString, options);
                m_Namespace.Options.EnablePrivileges = true;
                m_Namespace.Options.Impersonation    = ImpersonationLevel.Impersonate;
                m_Namespace.Connect();
                if (m_Namespace.IsConnected)
                {
                    return(true);
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                if (options == null || String.IsNullOrEmpty(options.Username) || autoLogon)
                {
                    using (var form = new AuthForm())
                    {
                        if (autoLogon)
                        {
                            AuthForm.ClearSavedPassword();
                        }

                        form.SetComputerName(Args.ComputerName);
                        autoLogon = form.AutoLogOn();
                        bool ok;
                        if (autoLogon)
                        {
                            ok = true;
                        }
                        else
                        {
                            ok = (form.ShowDialog() == DialogResult.OK);
                        }
                        if (ok)
                        {
                            m_Namespace = null;
                            options     = new ConnectionOptions
                            {
                                Username = form.UserName,
                                Password = form.UserPassword
                            };
                            goto TryAgainWithPassword;
                        }
                    }
                }
                else
                {
                    ShowCommonConnectionError(ex);
                }
            }
            catch (COMException ex)
            {
                if ((uint)ex.ErrorCode == 0x800706BA)
                {
                    ShowFirewallConnectionError();
                }
                else
                {
                    ShowCommonConnectionError(ex);
                }
            }
            //catch (Exception ex)
            //{
            //    ShowCommonConnectionError(ex);
            //}
            m_Namespace = null;
            return(false);
        }
コード例 #21
0
        AuthenticateUser
        (
            string clientId
        )
        {
            // Method members
            string authCode  = string.Empty;
            string postData  = string.Empty;
            string apiResult = string.Empty;

            try
            {
                // Create the initial authentication form for the user from TD
                // Ameritrade
                AuthForm authForm = new AuthForm(ApiMethod.GetAuthCode
                                                 .GetAttribute("Name")
                                                 .Replace("{account_id}", clientId), "https://127.0.0.1");

                // Show the authentication form
                authForm.ShowDialog();

                // Destroy the Windows Form Icon
                bool bDestroy = Helper.DestroyIcon(authForm.icon.Handle);
                if (!bDestroy)
                {
                    LogHelper.Log(LogLevel.Error, $"{Resx.GetString("WINDOWS_FORM_ICON_NOT_DESTROYED")}");
                }

                // Once here, the dialog control will be closed and the code
                // needed to request the first access token will be in the
                // querystring
                if (authForm.Query != null && !string.IsNullOrEmpty(authForm.Query["code"]))
                {
                    // Get the authorization code, which will be automatically
                    // url decoded
                    authCode = authForm.Query["code"];

                    // Authorization code is present in the query string. Form
                    // the url-encoded post data to retrieve an access token
                    postData  = $"grant_type=authorization_code&refresh_token=&access_type=offline&code={HttpUtility.UrlEncode(authCode)}";
                    postData += $"&client_id={HttpUtility.UrlEncode(clientId)}&redirect_uri={HttpUtility.UrlEncode("http://127.0.0.1")}";

                    // Get a TD Ameritrade REST API interface object, if needed
                    if (rest == null)
                    {
                        rest = new TDAmeritradeREST();
                    }

                    // Execute a query to the TD Ameritrade API for an access
                    // token
                    apiResult = rest.QueryApi(

                        // The method on the TD Ameritrade REST API being
                        // called
                        ApiMethod.PostAccessToken,

                        // The data helper method
                        ApiHelper.UrlEncodedData(

                            // The encoded form data
                            postData,

                            // Not using authentication in order to receive
                            // the first access token, which will then be
                            // used whenever subsequent authentication is
                            // needed
                            false
                            )
                        );

                    // Was an error encountered?
                    if (!apiResult.StartsWith("ERROR:"))
                    {
                        // NO: Get a json serializer based on the Token
                        // Model class
                        AuthToken token = Broker.DeserializeJson <AuthToken>(apiResult);

                        // Write the refresh token to encrypted file storage
                        token.Save(clientId);

                        // Return the refresh token
                        return(token);
                    }
                }
            }
            catch (Exception e)
            {
                // Log the error
                LogHelper.Log(LogLevel.Error, $"    {Resx.GetString("ERROR")}: {Resx.GetString("GETTING_ACCESS_TOKEN")}. " + e.Message);

                // Return an empty access token
                return(null);
            }


            // Log any errors
            LogHelper.Log(LogLevel.Error, apiResult);

            // Return an empty access token
            return(null);
        }
コード例 #22
0
 private void Login(int retry = 0)
 {
     if (IsValid())
         return;
     if (retry >= attempts)
         throw new InvalidCredentialsException("Wrong credentials! Authorization failed!");
     AuthForm a = new AuthForm(LoginUrl, Callback);
     a.ShowDialog();
     if (!IsValid())
         Login(retry + 1);
     else Save();
 }