api updates

This commit is contained in:
henrydays 2018-08-29 23:31:44 +01:00
parent efef0ade4d
commit 30e3a2e9d8
30 changed files with 462 additions and 62 deletions

View File

@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks;
using api.Dtos;
using api.Models;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
@ -13,7 +14,7 @@ using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace api.Controllers
{
{
[AllowAnonymous]
[Route("api/")]
[ApiController]
@ -24,52 +25,26 @@ namespace api.Controllers
private readonly IConfiguration config;
public UserManager<User> _userManager { get; }
public SignInManager<User> _signInManager { get; }
private readonly IMapper _mapper;
public AuthController(IConfiguration config,UserManager<User> UserManager, SignInManager<User> SignInManager)
public AuthController(IConfiguration config, UserManager<User> UserManager, SignInManager<User> SignInManager, IMapper mapper)
{
_mapper = mapper;
this.config = config;
_userManager = UserManager;
_signInManager = SignInManager;
}
[HttpPost("register")]
public async Task<IActionResult> Register(UserForRegisterDto UserForRegisterDto)
public async Task<IActionResult> Register(UserForRegisterDto userToRegister)
{
UserForRegisterDto.username = UserForRegisterDto.username.ToLower();
var userToCreate = new User
{
UserName = UserForRegisterDto.username,
FullName = UserForRegisterDto.fullname,
Gender= UserForRegisterDto.gender,
Age= UserForRegisterDto.age,
Phone= UserForRegisterDto.phone,
Email=UserForRegisterDto.email,
Adress=UserForRegisterDto.adress,
Country=UserForRegisterDto.country,
City=UserForRegisterDto.city,
linkedIn=UserForRegisterDto.linkedin,
LastLogin=UserForRegisterDto.lastlogin,
Registed=UserForRegisterDto.registed,
QRcode=UserForRegisterDto.qrcode,
Role=UserForRegisterDto.role,
Degree=UserForRegisterDto.degree,
SchoolYear=UserForRegisterDto.schoolyear,
ProfileIcon=UserForRegisterDto.profileicon,
Company=UserForRegisterDto.company,
Position=UserForRegisterDto.position,
About=UserForRegisterDto.about
};
var userToCreate = _mapper.Map<User>(userToRegister);
var result = await _userManager.CreateAsync(userToCreate, UserForRegisterDto.password);
var result = await _userManager.CreateAsync(userToCreate, userToRegister.password);
if(result.Succeeded)
if (result.Succeeded)
{
return StatusCode(201);
}
@ -80,41 +55,43 @@ namespace api.Controllers
[HttpPost("login")]
public async Task<IActionResult> Login(UserForLoginDto UserForLoginDto)
{
var user = await _userManager.FindByNameAsync(UserForLoginDto.Username);
var result = await _signInManager.CheckPasswordSignInAsync(user,UserForLoginDto.Password, false);
if(result.Succeeded)
var user = await _userManager.FindByNameAsync(UserForLoginDto.Username);
var result = await _signInManager.CheckPasswordSignInAsync(user, UserForLoginDto.Password, false);
if (result.Succeeded)
{
var appUser= await _userManager.Users.FirstOrDefaultAsync(u => u.NormalizedUserName == UserForLoginDto.Username.ToUpper());
return Ok(new {
token = GenerateJwtToken(appUser)
});
var appUser = await _userManager.Users.FirstOrDefaultAsync(u => u.NormalizedUserName == UserForLoginDto.Username.ToUpper());
return Ok(new
{
token = GenerateJwtToken(appUser)
});
}
return Unauthorized();
return Unauthorized();
}
private string GenerateJwtToken(User user){
var claims = new[]
{
private string GenerateJwtToken(User user)
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.UserName)
};
//obtem a key na app settings
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.GetSection("AppSettings:Token").Value));
//faz hashing da key na app settings
var creds= new SigningCredentials(key,SecurityAlgorithms.HmacSha512Signature);
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
//criamos um token
var tokenDescriptor = new SecurityTokenDescriptor
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
//data de expiração (atual + 24 horas)

View File

@ -1,7 +1,47 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using api.Data;
using api.Dtos;
using api.Models;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace api.Controllers
{
public class usersController
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IUsersRepository _repo;
private readonly IMapper _mapper;
public UsersController(IUsersRepository repo, IMapper mapper)
{
_mapper = mapper;
_repo = repo;
}
[HttpGet]
public async Task<IActionResult> GetUsers()
{
var users = await _repo.GetUsers();
var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);
return Ok(usersToReturn);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetUser(int id)
{
var user = await _repo.GetUser(id);
var userToReturn = _mapper.Map<UserForDetailedDto>(user);
return Ok(userToReturn);
}
}
}

View File

@ -12,6 +12,10 @@ namespace api.Data
public DbSet<Value> Values{get;set;}
public DbSet<Photo> Photos {get;set;}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);

View File

@ -0,0 +1,18 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using api.Models;
namespace api.Data
{
public interface IUsersRepository
{
void Add<T>(T enity) where T: class;
void Delete<T>(T entity) where T: class;
Task<bool> SaveAll();
Task<IEnumerable<User>> GetUsers();
Task<User> GetUser(int id);
}
}

View File

@ -0,0 +1,47 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using api.Models;
using Microsoft.EntityFrameworkCore;
namespace api.Data
{
public class UsersRepository : IUsersRepository
{
private readonly DataContext _context;
public UsersRepository(DataContext context)
{
this._context = context;
}
public void Add<T>(T enity) where T : class
{
_context.Add(enity);
}
public void Delete<T>(T entity) where T : class
{
_context.Remove(entity);
}
public async Task<User> GetUser(int id)
{
var user = await _context.Users.Include(p=>p.Photos).FirstOrDefaultAsync(u=>u.Id==id);
return user;
}
public async Task<IEnumerable<User>> GetUsers()
{
var users= await _context.Users.Include(p=>p.Photos).ToListAsync();
return users;
}
public async Task<bool> SaveAll()
{
return await _context.SaveChangesAsync()>0;
}
}
}

View File

@ -0,0 +1,14 @@
using System;
namespace api.Dtos
{
public class PhotosForDetailedDto
{
public int Id{get;set;}
public string Url{get;set;}
public string Description{get;set;}
public DateTime DateAdded{get;set;}
public bool IsMain{get;set;}
}
}

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
namespace api.Dtos
{
public class UserForDetailedDto
{
public string FullName {get;set;}
public string Gender {get;set;}
public int Age{get;set;}
public int Phone{get;set;}
public string University{get;set;}
public string Adress{get;set;}
public string Country{get;set;}
public string City{get;set;}
public string linkedIn{get;set;}
public DateTime LastLogin {get;set;}
public DateTime Registed{get;set;}
public string QRcode{get;set;}
public string Role{get;set;}
public string Degree{get;set;}
public int SchoolYear{get;set;}
public string ProfileIcon {get;set;}
public string Company{get;set;}
public string Position{get;set;}
public string About{get;set;}
public ICollection<PhotosForDetailedDto> Photos {get;set;}
}
}

View File

@ -0,0 +1,22 @@
using System;
namespace api.Dtos
{
public class UserForListDto
{
public string FullName {get;set;}
public string Gender {get;set;}
public int Age{get;set;}
public int Phone{get;set;}
public string University{get;set;}
public string Adress{get;set;}
public string linkedIn{get;set;}
public string QRcode{get;set;}
public string Degree{get;set;}
public string ProfileIcon {get;set;}
public string About{get;set;}
public string PhotoUrl{get;set;}
}
}

View File

@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using api.Models;
namespace api.Dtos
{
@ -31,6 +33,7 @@ namespace api.Dtos
public string company{get;set;}
public string position{get;set;}
public string about{get;set;}
public ICollection<Photo> Photos{get;set;}
}
}

View File

@ -0,0 +1,21 @@
using api.Dtos;
using api.Models;
using AutoMapper;
namespace api.Helpers
{
public class AutoMapperProfiles: Profile
{
public AutoMapperProfiles()
{
CreateMap<UserForRegisterDto,User>();
CreateMap<User,UserForListDto>();
CreateMap<User, UserForDetailedDto>();
CreateMap<Photo,PhotosForDetailedDto>();
}
}
}

View File

@ -9,7 +9,7 @@ using api.Data;
namespace api.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20180829010046_update")]
[Migration("20180829184152_update")]
partial class update
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -18,6 +18,28 @@ namespace api.Migrations
modelBuilder
.HasAnnotation("ProductVersion", "2.1.1-rtm-30846");
modelBuilder.Entity("api.Models.Photo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("DateAdded");
b.Property<string>("Description");
b.Property<bool>("IsMain");
b.Property<string>("Url");
b.Property<int>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Photos");
});
modelBuilder.Entity("api.Models.Role", b =>
{
b.Property<int>("Id")
@ -222,6 +244,14 @@ namespace api.Migrations
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("api.Models.Photo", b =>
{
b.HasOne("api.Models.User", "User")
.WithMany("Photos")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("api.Models.UserRole", b =>
{
b.HasOne("api.Models.Role", "Role")

View File

@ -186,6 +186,29 @@ namespace api.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Photos",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Url = table.Column<string>(nullable: true),
Description = table.Column<string>(nullable: true),
DateAdded = table.Column<DateTime>(nullable: false),
IsMain = table.Column<bool>(nullable: false),
UserId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Photos", x => x.Id);
table.ForeignKey(
name: "FK_Photos_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
@ -222,6 +245,11 @@ namespace api.Migrations
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Photos_UserId",
table: "Photos",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
@ -241,6 +269,9 @@ namespace api.Migrations
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "Photos");
migrationBuilder.DropTable(
name: "Values");

View File

@ -16,6 +16,28 @@ namespace api.Migrations
modelBuilder
.HasAnnotation("ProductVersion", "2.1.1-rtm-30846");
modelBuilder.Entity("api.Models.Photo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("DateAdded");
b.Property<string>("Description");
b.Property<bool>("IsMain");
b.Property<string>("Url");
b.Property<int>("UserId");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Photos");
});
modelBuilder.Entity("api.Models.Role", b =>
{
b.Property<int>("Id")
@ -220,6 +242,14 @@ namespace api.Migrations
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("api.Models.Photo", b =>
{
b.HasOne("api.Models.User", "User")
.WithMany("Photos")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("api.Models.UserRole", b =>
{
b.HasOne("api.Models.Role", "Role")

19
api/Models/Photo.cs Normal file
View File

@ -0,0 +1,19 @@
using System;
namespace api.Models
{
public class Photo
{
public int Id{get;set;}
public string Url {get;set;}
public string Description{get;set;}
public DateTime DateAdded {get;set;}
public bool IsMain {get;set;}
public User User{get;set;}
public int UserId{get;set;}
}
}

View File

@ -28,7 +28,7 @@ namespace api.Models
public string Position{get;set;}
public string About{get;set;}
public ICollection<UserRole> UserRoles{get;set;}
public ICollection<Photo> Photos {get;set;}
}
}

View File

@ -7,6 +7,7 @@ using System.Threading.Tasks;
using api.Data;
using api.Helpers;
using api.Models;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
@ -40,6 +41,10 @@ namespace api
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper();
services.AddScoped<IUsersRepository, UsersRepository>();
//define a connection string indicada em appsettings.json
services.AddDbContext<DataContext>(x=>x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

View File

@ -6,6 +6,8 @@
<Folder Include="wwwroot\"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.1"/>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.1"/>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="5.0.1"/>
</ItemGroup>
</Project>

Binary file not shown.

View File

@ -1,7 +1,7 @@
{
"runtimeTarget": {
"name": ".NETCoreApp,Version=v2.1",
"signature": "6cc7e1a7df8f862cfbd58129a47b8594cb80b76a"
"signature": "d4ece2566b606cdfecfe4a8e0ea4337bec322c2a"
},
"compilationOptions": {
"defines": [
@ -24,6 +24,7 @@
".NETCoreApp,Version=v2.1": {
"api/1.0.0": {
"dependencies": {
"AutoMapper.Extensions.Microsoft.DependencyInjection": "5.0.1",
"Microsoft.AspNetCore.All": "2.1.0",
"Microsoft.EntityFrameworkCore.SqlServer": "2.1.1",
"Microsoft.NETCore.App": "2.1.0"
@ -35,6 +36,35 @@
"api.dll": {}
}
},
"AutoMapper/7.0.1": {
"dependencies": {
"System.ValueTuple": "4.5.0"
},
"runtime": {
"lib/netcoreapp2.0/AutoMapper.dll": {
"assemblyVersion": "7.0.1.0",
"fileVersion": "7.0.1.0"
}
},
"compile": {
"lib/netcoreapp2.0/AutoMapper.dll": {}
}
},
"AutoMapper.Extensions.Microsoft.DependencyInjection/5.0.1": {
"dependencies": {
"AutoMapper": "7.0.1",
"Microsoft.Extensions.DependencyInjection.Abstractions": "2.1.1"
},
"runtime": {
"lib/netstandard2.0/AutoMapper.Extensions.Microsoft.DependencyInjection.dll": {
"assemblyVersion": "0.0.0.0",
"fileVersion": "5.0.1.0"
}
},
"compile": {
"lib/netstandard2.0/AutoMapper.Extensions.Microsoft.DependencyInjection.dll": {}
}
},
"Microsoft.EntityFrameworkCore/2.1.1": {
"dependencies": {
"Microsoft.EntityFrameworkCore.Abstractions": "2.1.1",
@ -3841,6 +3871,20 @@
"serviceable": false,
"sha512": ""
},
"AutoMapper/7.0.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-6xHbhsW09sWjjYuE1sqhYn25PQzB6UEUVPME5uhlaIz2NR2+L3+FGbVxvknJKug1BLp6VTLxDb5RcGXKMm0ieQ==",
"path": "automapper/7.0.1",
"hashPath": "automapper.7.0.1.nupkg.sha512"
},
"AutoMapper.Extensions.Microsoft.DependencyInjection/5.0.1": {
"type": "package",
"serviceable": true,
"sha512": "sha512-7MIq6D/ax3964iHXbL1L2ldUvl6IlKp0p1GZFzr6vlIhEVyp4CgJwOpisRLvIO7dP+kDtbY3Hb9yuPNCkfyBFg==",
"path": "automapper.extensions.microsoft.dependencyinjection/5.0.1",
"hashPath": "automapper.extensions.microsoft.dependencyinjection.5.0.1.nupkg.sha512"
},
"Microsoft.EntityFrameworkCore/2.1.1": {
"type": "package",
"serviceable": true,

Binary file not shown.

Binary file not shown.

View File

@ -1 +1 @@
30e9dae95a6e59aac28ec7765f632b5b766c0005
9ade57420cf6be893d4ff0d490f78cfa807f3a03

Binary file not shown.

Binary file not shown.

View File

@ -1,5 +1,5 @@
{
"version": 1,
"dgSpecHash": "Ifnq9Fh8VEzrOLQIjuwLS9T+Qa9IyUhxLbg2/sjYDpPJs08FyW3Fp2VuBlQAHYsawJVDMuu3YGMWdwyABNmeQQ==",
"dgSpecHash": "WgSIDO2aNXJM3+NVsQN85bnSYTnN+GLKLvAZ05u5LdW96kSbgEgrqrUsZF3u6AYOsqfgGrFItAR2SJyFsa6KKA==",
"success": true
}

View File

@ -2,6 +2,31 @@
"version": 3,
"targets": {
".NETCoreApp,Version=v2.1": {
"AutoMapper/7.0.1": {
"type": "package",
"dependencies": {
"System.ValueTuple": "4.5.0"
},
"compile": {
"lib/netcoreapp2.0/AutoMapper.dll": {}
},
"runtime": {
"lib/netcoreapp2.0/AutoMapper.dll": {}
}
},
"AutoMapper.Extensions.Microsoft.DependencyInjection/5.0.1": {
"type": "package",
"dependencies": {
"AutoMapper": "7.0.1",
"Microsoft.Extensions.DependencyInjection.Abstractions": "2.0.0"
},
"compile": {
"lib/netstandard2.0/AutoMapper.Extensions.Microsoft.DependencyInjection.dll": {}
},
"runtime": {
"lib/netstandard2.0/AutoMapper.Extensions.Microsoft.DependencyInjection.dll": {}
}
},
"Libuv/1.10.0": {
"type": "package",
"dependencies": {
@ -5261,6 +5286,38 @@
}
},
"libraries": {
"AutoMapper/7.0.1": {
"sha512": "6xHbhsW09sWjjYuE1sqhYn25PQzB6UEUVPME5uhlaIz2NR2+L3+FGbVxvknJKug1BLp6VTLxDb5RcGXKMm0ieQ==",
"type": "package",
"path": "automapper/7.0.1",
"files": [
"automapper.7.0.1.nupkg.sha512",
"automapper.nuspec",
"lib/net45/AutoMapper.dll",
"lib/net45/AutoMapper.pdb",
"lib/net45/AutoMapper.xml",
"lib/netcoreapp2.0/AutoMapper.dll",
"lib/netcoreapp2.0/AutoMapper.pdb",
"lib/netcoreapp2.0/AutoMapper.xml",
"lib/netstandard1.3/AutoMapper.dll",
"lib/netstandard1.3/AutoMapper.pdb",
"lib/netstandard1.3/AutoMapper.xml",
"lib/netstandard2.0/AutoMapper.dll",
"lib/netstandard2.0/AutoMapper.pdb",
"lib/netstandard2.0/AutoMapper.xml"
]
},
"AutoMapper.Extensions.Microsoft.DependencyInjection/5.0.1": {
"sha512": "7MIq6D/ax3964iHXbL1L2ldUvl6IlKp0p1GZFzr6vlIhEVyp4CgJwOpisRLvIO7dP+kDtbY3Hb9yuPNCkfyBFg==",
"type": "package",
"path": "automapper.extensions.microsoft.dependencyinjection/5.0.1",
"files": [
"automapper.extensions.microsoft.dependencyinjection.5.0.1.nupkg.sha512",
"automapper.extensions.microsoft.dependencyinjection.nuspec",
"lib/netstandard2.0/AutoMapper.Extensions.Microsoft.DependencyInjection.dll",
"lib/netstandard2.0/AutoMapper.Extensions.Microsoft.DependencyInjection.pdb"
]
},
"Libuv/1.10.0": {
"sha512": "GsCf4q+eyaI49rCPlgYxdxa1SQCysXFFdSJWdstrwxytg4+VPYLYrXD4AT2rjHVJ+UF7SSWX9CapWEYaU4ejVQ==",
"type": "package",
@ -13554,6 +13611,7 @@
},
"projectFileDependencyGroups": {
".NETCoreApp,Version=v2.1": [
"AutoMapper.Extensions.Microsoft.DependencyInjection >= 5.0.1",
"Microsoft.AspNetCore.All >= 2.1.0",
"Microsoft.EntityFrameworkCore.SqlServer >= 2.1.1",
"Microsoft.NETCore.App >= 2.1.0"
@ -13598,6 +13656,10 @@
"frameworks": {
"netcoreapp2.1": {
"dependencies": {
"AutoMapper.Extensions.Microsoft.DependencyInjection": {
"target": "Package",
"version": "[5.0.1, )"
},
"Microsoft.AspNetCore.All": {
"target": "Package",
"version": "[2.1.0, )"

Binary file not shown.