Skip to content

Commit

Permalink
Add comments displaying, register 16+, Avatar
Browse files Browse the repository at this point in the history
  • Loading branch information
razorbohan committed Jan 23, 2020
1 parent 363b925 commit df928fb
Show file tree
Hide file tree
Showing 28 changed files with 959 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@
<div class="col-md-6">
<form id="profile-form" method="post">
<div asp-validation-summary="All" class="text-danger"></div>
@if (string.IsNullOrEmpty(Model.Photo))
{
<img src="~/images/noimagefound.jpg" alt="photo" width="100" height="100">
}
else
{
<img src="~/images/@Model.Photo" alt="photo" width="100" height="100">
}
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" disabled />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ public IndexModel(
}

public string Username { get; set; }
public string Photo { get; set; }

[TempData]
public string StatusMessage { get; set; }
Expand All @@ -44,6 +45,7 @@ private async Task LoadAsync(ApplicationUser user)
var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

Username = userName;
Photo = user.Photo;

Input = new InputModel
{
Expand Down
12 changes: 11 additions & 1 deletion ITNews/ITNews/Areas/Identity/Pages/Account/Register.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

<div class="row">
<div class="col-md-4">
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
<form asp-route-returnUrl="@Model.ReturnUrl" method="post" enctype="multipart/form-data">
<h4>Create a new account.</h4>
<hr />
<div asp-validation-summary="All" class="text-danger"></div>
Expand All @@ -17,6 +17,16 @@
<input asp-for="Input.Email" class="form-control" />
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Age"></label>
<input asp-for="Input.Age" type="range" class="form-control" min="1" oninput="document.getElementById('rangeValLabel').innerHTML = this.value" />
<em id="rangeValLabel" style="font-style: normal;"></em>
<span style="display: block;" asp-validation-for="Input.Age" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Input.Photo"></label>
<input name="Input.Photo" type="file" accept="image/*" />
</div>
<div class="form-group">
<label asp-for="Input.Password"></label>
<input asp-for="Input.Password" class="form-control" />
Expand Down
30 changes: 28 additions & 2 deletions ITNews/ITNews/Areas/Identity/Pages/Account/Register.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using System.IO;
using Microsoft.AspNetCore.Hosting;

namespace ITNews.Areas.Identity.Pages.Account
{
Expand All @@ -24,17 +27,20 @@ public class RegisterModel : PageModel
private readonly UserManager<ApplicationUser> _userManager;
private readonly ILogger<RegisterModel> _logger;
private readonly IEmailSender _emailSender;
private readonly IWebHostEnvironment _env;

public RegisterModel(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILogger<RegisterModel> logger,
IEmailSender emailSender)
IEmailSender emailSender,
IWebHostEnvironment env)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = logger;
_emailSender = emailSender;
_env = env;
}

[BindProperty]
Expand All @@ -51,6 +57,14 @@ public class InputModel
[Display(Name = "Email")]
public string Email { get; set; }

[Required]
[Range(16, 99, ErrorMessage = "You must be at least 16 years old.")]
[Display(Name = "Age")]
public string Age { get; set; }

[Display(Name = "Photo")]
public IFormFile Photo { get; set; }

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
Expand All @@ -75,7 +89,19 @@ public async Task<IActionResult> OnPostAsync(string returnUrl = null)
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
string filename = null;
if (Input.Photo != null)
{
var ext = Path.GetExtension(Input.Photo.FileName);
filename = $@"{Guid.NewGuid()}{ext}";
var path = Path.Combine(_env.WebRootPath, "images", filename);
using (var fileStream = new FileStream(path, FileMode.Create))
{
Input.Photo.CopyTo(fileStream);
}
}

var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, Photo = filename };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
Expand Down
12 changes: 12 additions & 0 deletions ITNews/ITNews/ClientApp/src/components/Comment/Comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import './Comment.scss'
import React from 'react'

const Comment = (props) => {
return (
<div className='comment'>
{props.comment.body}
</div>
)
}

export default Comment
3 changes: 3 additions & 0 deletions ITNews/ITNews/ClientApp/src/components/Comment/Comment.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.comment{

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class CreateEditNews extends Component {
this.state = {
allTags: [],
allCategories: [],
news: null,

isEdit: false,

isAlert: false,
severity: 'success',
status: ''
Expand All @@ -22,6 +26,20 @@ class CreateEditNews extends Component {
async componentDidMount() {
await this.fetchTags();
await this.fetchCategories();

const { id } = this.props.match.params;
if (!!id) {
this.setState({
isEdit: true
}, async () => {
const reponse = await fetch(`/api/GetNews/${id}`);
const news = await reponse.json();

this.setState({
news
});
});
}
}

async fetchCategories() {
Expand Down Expand Up @@ -60,7 +78,7 @@ class CreateEditNews extends Component {
this.setState({
isAlert: true,
severity: 'success',
status: 'News successfuly created!'
status: 'News successfuly created!'
}, () => window.location.reload());
} else {
this.setState({
Expand All @@ -75,7 +93,7 @@ class CreateEditNews extends Component {
return (
<div className='admin'>
<div className='title'>
<h2>Add news</h2>
<h2>{this.state.isEdit ? 'Update news' : 'Add news'}</h2>
</div>

<div className='name'>
Expand Down Expand Up @@ -125,7 +143,7 @@ class CreateEditNews extends Component {
variant='contained'
color='primary'
onClick={() => this.handleCreate()}>
Create
{this.state.isEdit ? 'Update' : 'Create'}
</Button>

<Snackbar
Expand Down
2 changes: 1 addition & 1 deletion ITNews/ITNews/ClientApp/src/containers/Home/Home.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,9 @@ export default Home

//TODO: users editing page
//TODO: user profile page (photo, registration date)
//TODO: registration age (16+)
//TODO: comments, likes, rating

//TODO: news editing page (finish edit)
//TODO: news paging
//TODO: language changing (en, ru)
//TODO: night/day mode
13 changes: 12 additions & 1 deletion ITNews/ITNews/ClientApp/src/containers/ListNews/ListNews.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import './ListNews'
import React, { Component } from 'react'
import MaterialTable from 'material-table';
import { Button, Snackbar, IconButton } from '@material-ui/core';

export class ListNews extends Component {

Expand Down Expand Up @@ -64,13 +65,23 @@ export class ListNews extends Component {
}

async EditNews(id) {
this.props.history.push(`/createeditnews/${id}`);
if (!!id)
this.props.history.push(`/createeditnews/${id}`);
else this.props.history.push(`/createeditnews`);
}

render() {
return (
<div className='list-news'>

<Button
variant='contained'
color='primary'
style={{ margin: '10px' }}
onClick={() => this.EditNews()}>
Add News
</Button>

<MaterialTable
title='News'
columns={this.state.columns}
Expand Down
34 changes: 27 additions & 7 deletions ITNews/ITNews/ClientApp/src/containers/News/News.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,53 @@
import React, { Component } from 'react';
import './News.scss'
import NewsComponent from '../../components/News/News'
import Comment from '../../components/Comment/Comment'

class News extends Component {

constructor(props) {
super(props);

this.state = {
news: null
news: null,
comments: []
}
};

async componentDidMount() {
await this.fetchNews();
await this.fetchComments();
}

async fetchNews() {
const reponse = await fetch(`/api/GetNews/${this.props.match.params.id}`);
const news = await reponse.json();

this.setState({
news
});
this.setState({ news });
}

async fetchComments() {
const reponse = await fetch(`/api/GetNewsComments/${this.props.match.params.id}`);
const comments = await reponse.json();

this.setState({ comments });
}

render() {
const news = this.state.news;

return (
<NewsComponent
news={news}
isShort={false} />
<div className='news'>
<NewsComponent
news={news}
isShort={false} />

{this.state.comments.length > 0 ? this.state.comments.map(comment =>
<Comment
key={comment.id}
comment={comment} />
) : <p>No comments yet</p>}
</div>
);
}
}
Expand Down
33 changes: 31 additions & 2 deletions ITNews/ITNews/Controllers/ApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

namespace ITNews.Controllers
{
//[Authorize(Roles = "Administrator")]
[Authorize(Roles = "Administrator")]
[ApiController]
[Route("api")]
public class ApiController : ControllerBase
Expand Down Expand Up @@ -82,7 +82,7 @@ public IActionResult DeleteNews([FromBody] int id)

// POST: api/AddNews
[HttpPost("AddNews")]
public IActionResult AddNews(NewsModel newsModel)
public IActionResult AddNews(NewsViewModel newsModel)
{
var category = NewsService.GetCategories().FirstOrDefault(x => x.Name == newsModel.Category);
var tags = NewsService.GetTags().Where(x => newsModel.Tags.Contains(x.Name)).ToList();
Expand Down Expand Up @@ -132,5 +132,34 @@ public IEnumerable<Category> GetCategories()
{
return NewsService.GetCategories();
}

// GET: api/GetNewsComments/2
[AllowAnonymous]
[HttpGet("GetNewsComments/{id}")]
public IEnumerable<Comment> GetNewsComments(int id)
{
return NewsService.GetNewsComments(id);
}

// POST: api/AddNewsComments
[AllowAnonymous]
[HttpPost("AddNewsComments")]
public IActionResult AddNewsComments(CommentViewModel commentModel)
{
var news = NewsService.GetNews(commentModel.NewsId);

var comment = new Comment
{
Body = commentModel.Body,
UserId = commentModel.UserId,
News = news
};

//news.Comments.Add(comment);

NewsService.AddNewsComments(comment);

return Ok();
}
}
}
6 changes: 6 additions & 0 deletions ITNews/ITNews/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ public ApplicationDbContext(
DbContextOptions options,
IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
{
Database.EnsureCreated();
}

//protected override void OnModelCreating(ModelBuilder modelBuilder)
//{

//}
}
}
Loading

0 comments on commit df928fb

Please sign in to comment.