Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Yurii dev #92

Merged
merged 3 commits into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cmd/web/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ func main() {
app.GoogleClientSecret = "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"
app.GoogleRedirectURL = "http://localhost:8080/google-callback"

app.ModeratorPass = "123" //our secret pass for moders

//the list of games that are represented and will be covered on site.
app.GamesList = map[string]string{
"Lineage 2": "L2",
Expand Down
1 change: 1 addition & 0 deletions cmd/web/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func routes(a *config.AppConfig) http.Handler {
mux.HandleFunc("/personal_cabinet_threads", handler.Repo.GetAllThreadsForUserHandler)
mux.HandleFunc("/personal_cabinet_posts", handler.Repo.GetAllPostsForUserHandler)
mux.HandleFunc("/personal_cabinet_likes", handler.Repo.GetAllLikedPostsByUserIDHandler)
mux.HandleFunc("/personal_cabinet_user_type", handler.Repo.ChangeUserTypeResultHandler) //handler to change user type

mux.HandleFunc("/create_post_result", handler.Repo.CreatePostResultHandler)

Expand Down
2 changes: 2 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,6 @@ type AppConfig struct {
GoogleClientID string
GoogleClientSecret string
GoogleRedirectURL string

ModeratorPass string //added Moder pass to app config
}
45 changes: 45 additions & 0 deletions internal/handler/editUserTypeHandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package handler

import (
"net/http"
"strconv"
"strings"

"github.com/Pomog/ForumFFF/internal/models"
"github.com/Pomog/ForumFFF/internal/renderer"
)

// ChangeUserTypeResultHandler handles changing of user type
func (m *Repository) ChangeUserTypeResultHandler(w http.ResponseWriter, r *http.Request) {
sessionUserID := m.GetLoggedUser(w, r)
if sessionUserID == 0 {
setErrorAndRedirect(w, r, "unautorized", "/error-page")
return
}
personalCabinetUserID, err := strconv.Atoi(r.URL.Query().Get("userID"))
if err != nil {
setErrorAndRedirect(w, r, "could not convert string to int: strconv.Atoi(r.URL.Query().Get(userID))", "/error-page")
return
}
if sessionUserID != personalCabinetUserID {
setErrorAndRedirect(w, r, "only owner of cabinet can submit secret code", "/error-page")
return
}
inputPass := strings.TrimSpace(r.FormValue("changeUserType"))

if r.Method == http.MethodPost && inputPass == m.App.ModeratorPass {
user, _ := m.DB.GetUserByID(sessionUserID)
user.Type = "moder"
m.DB.EditUserType(user)

data := make(map[string]interface{})
data["userID"] = user.ID
renderer.RendererTemplate(w, "edit_user_type_result.page.html", &models.TemplateData{
Data: data,
})

} else {
http.Error(w, "wrong secret code", http.StatusMethodNotAllowed)
}

}
19 changes: 17 additions & 2 deletions internal/handler/loginHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ import (

// LoginHandler handles both GET and POST requests for the login page.
func (m *Repository) LoginHandler(w http.ResponseWriter, r *http.Request) {
userIDstring := r.URL.Query().Get("id")
if userIDstring != "" {
userID, err := strconv.Atoi(userIDstring)
if err != nil {
setErrorAndRedirect(w, r, "wrong URL", "/error-page")
return
}
err = m.DB.DelSessionByUserID(userID)
if err != nil {
setErrorAndRedirect(w, r, err.Error(), "/error-page")
return
}
}

if r.Method == http.MethodGet {
var emptyLogin models.User
data := make(map[string]interface{})
Expand Down Expand Up @@ -62,8 +76,9 @@ func (m *Repository) LoginHandler(w http.ResponseWriter, r *http.Request) {
}

cookie := &http.Cookie{
Name: strconv.Itoa(userID),
Value: m.App.UserLogin.String(),
Name: strconv.Itoa(userID),
Value: m.App.UserLogin.String(),
HttpOnly: true,
}
http.SetCookie(w, cookie)

Expand Down
8 changes: 8 additions & 0 deletions internal/handler/staticHelperHendlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ func (m *Repository) PrivatPolicyHandler(w http.ResponseWriter, r *http.Request)

// PersonaCabinetHandler hanles the personal cabinet of selected user.
func (m *Repository) PersonaCabinetHandler(w http.ResponseWriter, r *http.Request) {
sessionUserID := m.GetLoggedUser(w, r)
if sessionUserID == 0 {
setErrorAndRedirect(w, r, "unautorized", "/error-page")
return
}

if r.Method == http.MethodGet {
userID, _ := strconv.Atoi(r.URL.Query().Get("userID"))
var personalInfo models.User
Expand All @@ -103,10 +109,12 @@ func (m *Repository) PersonaCabinetHandler(w http.ResponseWriter, r *http.Reques
personalInfo.LastName = user.LastName
personalInfo.Picture = user.Picture
personalInfo.UserName = user.UserName
personalInfo.Type = user.Type //will show type of user in personal cabinet
totalPosts, _ := m.DB.GetTotalPostsAmmountByUserID(personalInfo.ID)
data := make(map[string]interface{})
data["personal"] = personalInfo
data["totalPosts"] = totalPosts
data["loggedAsID"] = sessionUserID

renderer.RendererTemplate(w, "personal.page.html", &models.TemplateData{
Data: data,
Expand Down
31 changes: 18 additions & 13 deletions internal/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,17 @@ type User struct {
Created time.Time
Picture string
LastActivity time.Time
Type string
}

type Thread struct {
ID int
Subject string
Created time.Time
UserID int
Image string
Category string
ID int
Subject string
Created time.Time
UserID int
Image string
Category string
Classification string
}

type ThreadDataForMainPage struct {
Expand All @@ -36,6 +38,7 @@ type ThreadDataForMainPage struct {
ThreadID int
Image string
Category string
Classification string
}

type PostDataForThemePage struct {
Expand All @@ -51,16 +54,18 @@ type PostDataForThemePage struct {
UserPostsAmmount int
Likes int
Dislikes int
Classification string
}

type Post struct {
ID int
Subject string
Content string
Created time.Time
ThreadId int
UserID int
Image string
ID int
Subject string
Content string
Created time.Time
ThreadId int
UserID int
Image string
Classification string
}

type Votes struct {
Expand Down
55 changes: 46 additions & 9 deletions internal/repository/dbrepo/sqllite.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func (m *SqliteBDRepo) GetUserByID(ID int) (models.User, error) {

row := m.DB.QueryRowContext(ctx, query, ID)

err := row.Scan(&user.ID, &user.UserName, &user.Password, &user.FirstName, &user.LastName, &user.Email, &user.Created, &user.Picture, &user.LastActivity)
err := row.Scan(&user.ID, &user.UserName, &user.Password, &user.FirstName, &user.LastName, &user.Email, &user.Created, &user.Picture, &user.LastActivity, &user.Type)
if err != nil {
return user, err
}
Expand Down Expand Up @@ -96,7 +96,7 @@ func (m *SqliteBDRepo) GetThreadByID(ID int) (models.Thread, error) {

row := m.DB.QueryRowContext(ctx, query, ID)

err := row.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category)
err := row.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category, &thread.Classification)
if err != nil {
return thread, err
}
Expand All @@ -115,7 +115,7 @@ func (m *SqliteBDRepo) GetPostByID(ID int) (models.Post, error) {

row := m.DB.QueryRowContext(ctx, query, ID)

err := row.Scan(&post.ID, &post.Subject, &post.Content, &post.Created, &post.ThreadId, &post.UserID, &post.Image)
err := row.Scan(&post.ID, &post.Subject, &post.Content, &post.Created, &post.ThreadId, &post.UserID, &post.Image, &post.Classification)
if err != nil {
return post, err
}
Expand Down Expand Up @@ -334,7 +334,7 @@ func (m *SqliteBDRepo) GetAllPostsFromThread(threadID int) ([]models.Post, error

for rows.Next() {
var post models.Post
err := rows.Scan(&post.ID, &post.Subject, &post.Content, &post.Created, &post.ThreadId, &post.UserID, &post.Image)
err := rows.Scan(&post.ID, &post.Subject, &post.Content, &post.Created, &post.ThreadId, &post.UserID, &post.Image, &post.Classification)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -363,7 +363,7 @@ func (m *SqliteBDRepo) GetAllPostsByUserID(userID int) ([]models.Post, error) {

for rows.Next() {
var post models.Post
err := rows.Scan(&post.ID, &post.Subject, &post.Content, &post.Created, &post.ThreadId, &post.UserID, &post.Image)
err := rows.Scan(&post.ID, &post.Subject, &post.Content, &post.Created, &post.ThreadId, &post.UserID, &post.Image, &post.Classification)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -421,7 +421,7 @@ func (m *SqliteBDRepo) GetAllThreadsByUserID(userID int) ([]models.Thread, error

for rows.Next() {
var thread models.Thread
err := rows.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category)
err := rows.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category, &thread.Classification)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -449,7 +449,7 @@ func (m *SqliteBDRepo) GetAllThreads() ([]models.Thread, error) {

for rows.Next() {
var thread models.Thread
err := rows.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category)
err := rows.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category, &thread.Classification)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -651,7 +651,7 @@ func (m *SqliteBDRepo) GetSearchedThreads(search string) ([]models.Thread, error

for rows.Next() {
var thread models.Thread
err := rows.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category)
err := rows.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category, &thread.Classification)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -679,7 +679,7 @@ func (m *SqliteBDRepo) GetSearchedThreadsByCategory(search string) ([]models.Thr

for rows.Next() {
var thread models.Thread
err := rows.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category)
err := rows.Scan(&thread.ID, &thread.Subject, &thread.Created, &thread.UserID, &thread.Image, &thread.Category, &thread.Classification)
if err != nil {
return nil, err
}
Expand All @@ -688,3 +688,40 @@ func (m *SqliteBDRepo) GetSearchedThreadsByCategory(search string) ([]models.Thr

return threads, nil
}

//EditUserType changes type of user from "user" to "moder"
func (m *SqliteBDRepo) EditUserType(user models.User) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

stmt := `UPDATE users
SET type = $1
WHERE id = $2;
`
_, err := m.DB.ExecContext(ctx, stmt,
user.Type,
user.ID,
)

if err != nil {
return err
}
return nil
}

func (m *SqliteBDRepo) DelSessionByUserID(userID int) error {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

stmt := `delete from sessionId
where userID = $1
`
_, err := m.DB.ExecContext(ctx, stmt,
userID,
)

if err != nil {
return err
}
return nil
}
2 changes: 2 additions & 0 deletions internal/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,6 @@ type DatabaseInt interface {
GetAllThreadsByUserID(userID int) ([]models.Thread, error)
GetAllPostsByUserID(userID int) ([]models.Post, error)
GetAllLikedPostsByUserID(userID int) ([]models.Post, error)
EditUserType(user models.User) error
DelSessionByUserID(userID int) error
}
19 changes: 16 additions & 3 deletions internal/repository/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ var userTable = `CREATE TABLE IF NOT EXISTS users (
last_name varchar(100) DEFAULT "",
email varchar(254) DEFAULT "",
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
picture TEXT DEFAULT "static/ava/pomog_ava.png",
picture TEXT DEFAULT "static/ava/ava1.png",
last_activity TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`

Expand Down Expand Up @@ -51,9 +51,17 @@ var sessionIdTable = `CREATE TABLE IF NOT EXISTS sessionId (
FOREIGN KEY (userID) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE
);`

var guestUser = `INSERT INTO users (username, password, first_name, last_name, email)
VALUES ('guest', '123456', 'Guest', 'User', 'guest@gmail.com');`
var guestUser = `INSERT INTO users (username, password, first_name, last_name, email, type)
VALUES ('guest', '123456', 'Guest', 'User', 'guest@gmail.com', 'guest');`

var addClassificationToPost = `ALTER TABLE post
ADD COLUMN classification VARCHAR(50) DEFAULT '';`

var addClassificationToThread = `ALTER TABLE thread
ADD COLUMN classification VARCHAR(50) DEFAULT '';`

var addUserType = `ALTER TABLE users
ADD COLUMN type VARCHAR(50) DEFAULT 'user';`

func getQuerys() []string {
var sqlQuerys []string
Expand All @@ -62,5 +70,10 @@ func getQuerys() []string {
sqlQuerys = append(sqlQuerys, postTable)
sqlQuerys = append(sqlQuerys, votesTable)
sqlQuerys = append(sqlQuerys, sessionIdTable)

sqlQuerys = append(sqlQuerys, addClassificationToPost)
sqlQuerys = append(sqlQuerys, addClassificationToThread)
sqlQuerys = append(sqlQuerys, addUserType)

return sqlQuerys
}
Binary file modified mainDB.db
Binary file not shown.
Binary file added static/ava/face.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/ava/fp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/ava/guestLogo2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/ava/Варлок Котяра.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added static/post_images/fp.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 16 additions & 0 deletions template/edit_user_type_result.page.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{{template "body" .}}

{{define "centralPart"}}
<div class="container custom-container">
{{$userID := index .Data "userID"}}
<div class="mt-3">
<p>Congratulations! Your upgrade has been approved. You're now wielding the mighty powers
of a Moderator! Time to sprinkle some stardust and wield that virtual hammer with grace.
🌟 And hey, remember, with great power comes great... jokes! How about this one: Why don't
programmers like nature? It has too many bugs! 😄 Welcome to the Moderator club, where puns
and power collide!</p>
<br><a href="/personal_cabinet?userID={{$userID}}"><h2>Return to your cabinet...</h2></a>
</div>
</div>

{{end}}
6 changes: 3 additions & 3 deletions template/main.layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

<nav id="navbarTop" class="navbar navbar-expand-lg navbar-dark navBar">
<div class="container-fluid">
<img src="static\logo\10.png" class="logo_img" alt="logo"><a class="navbar-brand" href="/">Fan.Forge.Forum.</a>
<img src="static\logo\10.png" class="logo_img" alt="logo"><a class="navbar-brand" href="/home">Fan.Forge.Forum.</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
Expand Down Expand Up @@ -54,9 +54,9 @@
<div>
{{$loggedAs := index .Data "loggedAs"}}
{{$loggedAsID := index .Data "loggedAsID"}}
{{ if $loggedAs }}
{{ if $loggedAsID }}
<a class="" href="/personal_cabinet?userID={{$loggedAsID}}">{{$loggedAs}}</a>
<a class="btn btn-light login" href="/login">Logout</a>
<a class="btn btn-light login" href="/login?id={{$loggedAsID}}">Logout</a>
{{ else }}
<a class="btn btn-light login" href="/login">Login</a>
<a class="btn btn-light register" href="/registration">Register</a>
Expand Down
Loading