Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data.SqlClient;
- using System.Text;
- using System.Security.Cryptography;
- using RCKlubben.Models;
- namespace RCKlubben.Factories
- {
- public class UserFactory : AutoFac<User>
- {
- public static string HashPassword(string password)
- {
- // Get byte values for each character in password and store in byte array.
- byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
- // Hash the bytes
- SHA256 sha = new SHA256Managed();
- var computedPassword = sha.ComputeHash(passwordBytes);
- // Format the hashed bytes back to a string.
- var hashedPassword = string.Empty;
- foreach (var b in computedPassword)
- {
- hashedPassword += String.Format("{0:x2}", b);
- }
- return hashedPassword;
- }
- public User Login(string username, string password)
- {
- Mapper<User> mapper = new Mapper<User>();
- using (var cmd = new SqlCommand("SELECT * FROM [user] WHERE Username=@Username AND Password=@Password",
- Conn.CreateConnection()))
- {
- cmd.Parameters.AddWithValue("@Username", username);
- cmd.Parameters.AddWithValue("@Password", HashPassword(password));
- var r = cmd.ExecuteReader();
- User user = new User();
- if (r.Read())
- {
- user = mapper.Map(r);
- }
- r.Close();
- cmd.Connection.Close();
- if (user.Id > 0)
- {
- // Set the users session so he/she is logged in.
- HttpContext.Current.Session["UserId"] = user.Id;
- }
- return user;
- }
- }
- public User Login(User user)
- {
- return Login(user.Username, user.Password);
- }
- public User Register(string username, string password)
- {
- // Create the new user model.
- User user = new User
- {
- Username = username,
- Password = HashPassword(password),
- };
- var id = Insert(user);
- return Get(id);
- }
- public User Register(User user)
- {
- return Register(user.Username, user.Password);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement