Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using PremiumSMS.Models;
- using Microsoft.AspNetCore.Http;
- using Microsoft.EntityFrameworkCore;
- namespace PremiumSMS.Library.Authorization
- {
- public class Login
- {
- private string _username;
- private string _password;
- private readonly DatabaseContext _db = new DatabaseContext();
- private HttpContext _context;
- public Login(HttpContext context)
- {
- _context = context;
- }
- public bool CreateAuthentication(string username, string password)
- {
- _username = username;
- _password = password;
- if (CheckExistsAccount())
- {
- CreateSessionKey();
- return true;
- }
- return false;
- }
- public bool CheckAuthentication()
- {
- int count = 0;
- if(!string.IsNullOrEmpty(_context.Session.GetString("SessionKey")))
- {
- count = (from a in _db.Users
- where a.SessionKey == _context.Session.GetString("SessionKey")
- select a).Count();
- }
- if (count != 0)
- {
- return true;
- }
- return false;
- }
- public void DestroyAuthentication()
- {
- DestroySessionKey();
- _context.Session.Remove("SessionKey");
- }
- public void CreateSessionKey()
- {
- string sessionKey = Secure.CreateKey();
- var user = (from a in _db.Users
- where a.Username == _username
- select a).FirstOrDefault();
- if (user != null)
- {
- user.SessionKey = sessionKey;
- _db.Entry(user).State = EntityState.Modified;
- _db.SaveChanges();
- }
- _context.Session.SetString("SessionKey", sessionKey);
- }
- public void DestroySessionKey()
- {
- var user = (from a in _db.Users
- where a.SessionKey == _context.Session.GetString("SessionKey")
- select a).FirstOrDefault();
- if (user != null)
- {
- user.SessionKey = null;
- _db.Entry(user).State = EntityState.Modified;
- _db.SaveChanges();
- }
- }
- public bool CheckExistsAccount()
- {
- string securedPassword = Secure.HashString(_password);
- var numberAccounts = (from a in _db.Users
- where a.Username == _username && a.Password == securedPassword
- select a).Count();
- if (numberAccounts == 1)
- {
- return true;
- }
- return false;
- }
- public User GetUserObject()
- {
- var user = (from a in _db.Users
- where a.SessionKey == _context.Session.GetString("SessionKey")
- select a).FirstOrDefault();
- return user;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement