Skip to content

Instantly share code, notes, and snippets.

View nishanc's full-sized avatar
🚀
This is the way!

Nishan Chathuranga Wickramarathna nishanc

🚀
This is the way!
View GitHub Profile
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using JWTAuth.API.Data;
using Microsoft.EntityFrameworkCore;
namespace JWTAuth.API.Controllers
{
namespace JWTAuth.API.Models
{
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public byte[] PasswordHash { get; set; }
public byte[] PasswordSalt { get; set; }
}
}
using JWTAuth.API.Models;
using Microsoft.EntityFrameworkCore;
namespace JWTAuth.API.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) {}
public DbSet<Value> Values { get; set; }
public DbSet<User> Users { get; set; }
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace JWTAuth.API.Migrations
{
public partial class AddedUserModel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
using System.Threading.Tasks;
using JWTAuth.API.Models;
namespace JWTAuth.API.Data
{
public interface IAuthRepository
{
Task<User> Register(User user, string password);
Task<User> Login(string username, string pasword);
Task<bool> UserExists(string username);
using System.Threading.Tasks;
namespace JWTAuth.API.Data
{
public class AuthRepository : IAuthRepository
{
public async Task<User> Login(string username, string password)
{
}
public async Task<User> Login(string username, string password)
{
var user = await _context.Users.FirstOrDefaultAsync(x => x.Username == username); //Get user from database.
if(user == null)
return null; // User does not exist.
if(!VerifyPassword(password, user.PasswordHash,user.PasswordSalt))
return null;
return user;
public async Task<bool> UserExists(string username)
{
if (await _context.Users.AnyAsync(x => x.Username == username))
return true;
return false;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers()
.AddNewtonsoftJson();
services.AddScoped<IAuthRepository, AuthRepository>();
}
using Microsoft.AspNetCore.Mvc;
namespace JWTAuth.API.Controllers
{
public class AuthController : Controller
{
}
}