Skip to content

Commit

Permalink
Merge pull request #44 from Pomog/den_dev
Browse files Browse the repository at this point in the history
guest user is added, also theme and post are linked to users
  • Loading branch information
Pomog authored Dec 11, 2023
2 parents 985aac5 + e0392fd commit f1c4952
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 57 deletions.
116 changes: 68 additions & 48 deletions internal/handler/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,20 @@ func (m *Repository) RegisterHandler(w http.ResponseWriter, r *http.Request) {
// It renders the "home.page.html" template to the provided HTTP response writer.
func (m *Repository) HomeHandler(w http.ResponseWriter, r *http.Request) {
var UserID int

uuid := m.App.UserLogin
if uuid.String() == "" {
http.Redirect(w, r, "/login", http.StatusSeeOther)
m.App.InfoLog.Println("Could not get uuid in HomeHandler")
}

for _, cookie := range r.Cookies() {
if cookie.Value != "" {
userID, err := m.DB.GetUserIDForSessionID(cookie.Value)
if err != nil {
setErrorAndRedirect(w, r, "Could not get UserID from Cookies m.DB.GetUserIDForSessionID", "/error-page")
if cookie.Value == uuid.String() {
userID, _ := m.DB.GetUserIDForSessionID(cookie.Value)
if UserID = userID; UserID != 0 {
break
}
UserID = userID

}
}

Expand All @@ -237,6 +244,7 @@ func (m *Repository) HomeHandler(w http.ResponseWriter, r *http.Request) {
var user models.User
user, _ = m.DB.GetUserByID(thread.UserID)
var info models.ThreadDataForMainPage
info.ThreadID = thread.ID
info.Subject = thread.Subject
info.Created = thread.Created.Format("2006-01-02 15:04:05")

Expand All @@ -255,23 +263,31 @@ func (m *Repository) HomeHandler(w http.ResponseWriter, r *http.Request) {
}

data := make(map[string]interface{})

loggedUser, _ := m.DB.GetUserByID(UserID)
data["threads"] = threadsInfo
data["loggedAs"] = loggedUser.UserName

renderer.RendererTemplate(w, "home.page.html", &models.TemplateData{
Data: data,
})
} else if r.Method == http.MethodPost {
loggedUser, _ := m.DB.GetUserByID(UserID)
userName:=loggedUser.UserName
if userName == "guest"{
setErrorAndRedirect(w, r, "Guests can not create Themes and Posts, please log in or register!", "/error-page")
}
thread := models.Thread{
Subject: r.FormValue("message-text"),
UserID: UserID,
}

err := m.DB.CreateThread(thread)
id, err := m.DB.CreateThread(thread)
if err != nil {
setErrorAndRedirect(w, r, "Could not create a thread", "/error-page")
}
http.Redirect(w, r, "/theme", http.StatusPermanentRedirect)

http.Redirect(w, r, fmt.Sprintf("/theme?threadID=%d", id), http.StatusPermanentRedirect)

Check failure on line 289 in internal/handler/handlers.go

View workflow job for this annotation

GitHub Actions / build

undefined: fmt


}

Expand All @@ -290,59 +306,63 @@ func getUserThatCreatedLastPost(posts []models.Post) int {
return id
}

func getThreadIDFromCookies(r *http.Request) int {
return 2
func getThreadIDFromURLquery(w http.ResponseWriter, r *http.Request) int {
threadID, err := strconv.Atoi(r.URL.Query().Get("threadID"))
if err != nil {
setErrorAndRedirect(w, r, "Could not get all posts from thread", "/error-page")
}
return threadID
}

// MainHandler is a method of the Repository struct that handles requests to the main page.
// It renders the "home.page.html" template to the provided HTTP response writer.
func (m *Repository) ThemeHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
threadID := getThreadIDFromCookies(r)
posts, err := m.DB.GetAllPostsFromThread(threadID)
if err != nil {
setErrorAndRedirect(w, r, "Could not get all posts from thread", "/error-page")
}

var postsInfo []models.PostDataForThemePage

for _, post := range posts {
var user models.User
user, err = m.DB.GetUserByID(post.UserID)
if err != nil {
setErrorAndRedirect(w, r, "Could not get user by id", "/error-page")
}
var info models.PostDataForThemePage
info.Subject = post.Subject
info.Created = post.Created.Format("2006-01-02 15:04:05")
info.Content = post.Content
info.PictureUserWhoCreatedPost = user.Picture
info.UserNameWhoCreatedPost = user.UserName
postsInfo = append(postsInfo, info)
}
threadID := getThreadIDFromURLquery(w, r)

data := make(map[string]interface{})
posts, err := m.DB.GetAllPostsFromThread(threadID)
if err != nil {
setErrorAndRedirect(w, r, "Could not get all posts from thread", "/error-page")
}

data["posts"] = postsInfo
var postsInfo []models.PostDataForThemePage

mainThread, err := m.DB.GetThreadByID(getThreadIDFromCookies(r))
for _, post := range posts {
var user models.User
user, err = m.DB.GetUserByID(post.UserID)
if err != nil {
setErrorAndRedirect(w, r, "Could not get thread by id", "/error-page")
setErrorAndRedirect(w, r, "Could not get user by id", "/error-page")
}
var info models.PostDataForThemePage
info.Subject = post.Subject
info.Created = post.Created.Format("2006-01-02 15:04:05")
info.Content = post.Content
info.PictureUserWhoCreatedPost = user.Picture
info.UserNameWhoCreatedPost = user.UserName
postsInfo = append(postsInfo, info)
}

creator, err := m.DB.GetUserByID(mainThread.UserID)
if err != nil {
setErrorAndRedirect(w, r, "Could not get user as creator", "/error-page")
}
data := make(map[string]interface{})

data["creatorName"] = creator.UserName
data["creatorImg"] = creator.Picture
data["mainThreadName"] = mainThread.Subject
data["mainThreadCreatedTime"] = mainThread.Created.Format("2006-01-02 15:04:05")
renderer.RendererTemplate(w, "theme.page.html", &models.TemplateData{
Data: data,
})
data["posts"] = postsInfo

mainThread, err := m.DB.GetThreadByID(threadID)
if err != nil {
setErrorAndRedirect(w, r, "Could not get thread by id", "/error-page")
}

creator, err := m.DB.GetUserByID(mainThread.UserID)
if err != nil {
setErrorAndRedirect(w, r, "Could not get user as creator", "/error-page")
}

data["creatorName"] = creator.UserName
data["creatorImg"] = creator.Picture
data["mainThreadName"] = mainThread.Subject
data["mainThreadCreatedTime"] = mainThread.Created.Format("2006-01-02 15:04:05")
renderer.RendererTemplate(w, "theme.page.html", &models.TemplateData{
Data: data,
})

}

// ErrorPage handles the "/error-page" route
Expand Down
1 change: 1 addition & 0 deletions internal/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type ThreadDataForMainPage struct {
PictureUserWhoCreatedThread string
PictureUserWhoCreatedLastPost string
Posts []Post
ThreadID int
}

type PostDataForThemePage struct {
Expand Down
15 changes: 15 additions & 0 deletions internal/repository/db_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ func MakeDBTables() (*sql.DB, error) {
return dbConn.SQL, err
}
}
userExist,_:=userExists(dbConn.SQL, "guest")
if !userExist{
dbConn.SQL.Exec(guestUser)
}

return dbConn.SQL, nil
}
Expand All @@ -56,3 +60,14 @@ func testDB(db *sql.DB) error {
err := db.Ping()
return err
}

func userExists(db *sql.DB, username string) (bool, error) {
// Check if the user with the given username exists.
query := "SELECT COUNT(*) FROM users WHERE username = ?"
var count int
err := db.QueryRow(query, username).Scan(&count)
if err != nil {
return false, err
}
return count > 0, nil
}
12 changes: 8 additions & 4 deletions internal/repository/dbrepo/sqllite.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func (m *SqliteBDRepo) CreateUser(r models.User) error {
return nil
}

func (m *SqliteBDRepo) CreateThread(thread models.Thread) error {
func (m *SqliteBDRepo) CreateThread(thread models.Thread) (int64, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

Expand All @@ -121,15 +121,19 @@ func (m *SqliteBDRepo) CreateThread(thread models.Thread) error {
values ($1, $2)
`

_, err := m.DB.ExecContext(ctx, stmt,
sqlRes, err := m.DB.ExecContext(ctx, stmt,
thread.Subject,
thread.UserID,
)

if err != nil {
return err
return 0, err
}
return nil
id, err := sqlRes.LastInsertId()
if err != nil {
return 0, err
}
return id, nil
}

// CreatePost insert post into SQLite DB
Expand Down
4 changes: 2 additions & 2 deletions internal/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ type DatabaseInt interface {
UserPresent(userName, email string) (bool, error)
UserPresentLogin(email, password string) (int, error)
CreateUser(r models.User) error
CreateThread(thread models.Thread) error
CreateThread(thread models.Thread) (int64, error)
CreatePost(post models.Post) error
IsThreadExist(thread models.Thread) (bool, error)
GetAllPostsFromThread(threadID int) ([]models.Post, error)
GetUserByID(ID int) (models.User, error)
GetAllThreads() ([]models.Thread, error)
GetThreadByID(ID int) (models.Thread, error)
GetSessionIDForUserID(userID int) (string, error)
GetUserIDForSessionID(sessionID string) (int, error)
GetUserIDForSessionID(sessionID string) (int, error)
InsertSessionintoDB(sessionID string, userID int) error
}
4 changes: 4 additions & 0 deletions internal/repository/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ 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');
);`

func getQuerys() []string {
var sqlQuerys []string
sqlQuerys = append(sqlQuerys, userTable)
Expand Down
Binary file added static/ava/avaNew.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 5 additions & 2 deletions template/home.page.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
{{template "body" .}}

{{define "centralPart"}}
{{$loggedAs := index .Data "loggedAs"}}
<br>
<h3> Logged As: {{$loggedAs}}</h3>
<div class="container custom-container">
<table class="table border-success forumTable whiteLink mt-3">
<thead class="containerHead">
Expand Down Expand Up @@ -47,8 +50,8 @@ <h1 class="modal-title fs-5" id="createNewTopicModalLabel">What this topic will

<tr>
<td>
<!-- 1column -->
<a href="/theme">
<!-- 1column -->
<a href="/theme?threadID={{ .ThreadID}}">
<img src="{{ .PictureUserWhoCreatedThread }}" class="logo_img" alt="/static/logo/message_icon2.png"><strong>&nbsp;{{ .Subject }} </strong>
<br>Created by: {{ .UserNameWhoCreatedThread}}<br>
Topic created: {{ .Created}}
Expand Down
10 changes: 10 additions & 0 deletions template/login.page.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ <h1>Login</h1>
</div>
<button type="submit" class="btn btn-light">Login</button>
</form>
<form action="" method="post">
<!-- Hidden input field with pre-filled data -->
<input type="hidden" name="emailLogIn" value="guest@gmail.com">
<input type="hidden" name="passwordLogIn" value="123456">

<!-- Button for submitting the form -->
<br>
<button type="submit" class="btn btn-warning">Enter As Guest</button>
</form>

</div>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion template/main.layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
<button class="btn btn-outline-light" type="submit">Search</button>
</form>
<div>
<a class="btn btn-light login" href="/login">Loging</a>
<a class="btn btn-light login" href="/login">Login</a>
<a class="btn btn-light register" href="/registration">Register</a>
</div>
</div>
Expand Down

0 comments on commit f1c4952

Please sign in to comment.