BCR.UserDatabase.LoginUser C# (CSharp) Method

LoginUser() public static method

public static LoginUser ( string username, string password ) : string
username string
password string
return string
        public static string LoginUser(string username, string password)
        {
            NameValueCollection result = Database.Instance.QuerySingle("SELECT * FROM user WHERE username = '" + username + "' COLLATE NOCASE LIMIT 1;");
              if (result == null)
            return null;

              SaltedHash.SaltedHash sh = new SaltedHash.SaltedHash();
              if (!sh.VerifyHashString(password, result["password"], result["salt"]))
              {
            // invalid password
            Console.WriteLine("Invalid password for user " + username);
            return null;
              }

              //now that the user is validated, create an api key that can be used for subsequent requests
              var apiKey = Guid.NewGuid().ToString();

              Database.Instance.ExecuteNonQuery("INSERT INTO user_apikeys (user_id, apikey) VALUES (" + result["id"] + ", '" + apiKey + "');");

              return apiKey;
        }

Usage Example

Beispiel #1
0
        public AuthModule()
            : base(Database.Instance.GlobalSettings.url_base + "/auth")
        {
            ///////////////////////////////////////////////////////////////////////////////////////////
            // Login
            // The Post["/"] method returns the api key for subsequent REST calls.
            Post["/"] = x =>
            {
                string apiKey = UserDatabase.LoginUser((string)this.Request.Form.Username,
                                                       (string)this.Request.Form.Password);

                return(string.IsNullOrEmpty(apiKey)
                               ? new Response {
                    StatusCode = HttpStatusCode.Unauthorized
                }
                               : this.Response.AsJson(new { ApiKey = apiKey }));
            };

            ///////////////////////////////////////////////////////////////////////////////////////////
            // Logout
            // Destroy the api key.
            Delete["/"] = x =>
            {
                var apiKey = (string)this.Request.Form.ApiKey;
                UserDatabase.RemoveApiKey(apiKey);
                return(new Response {
                    StatusCode = HttpStatusCode.OK
                });
            };
        }