Skip to content

todo crud with grpc gateway (#12) #13

New issue

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

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

Already on GitHub? # to your account

Open
wants to merge 14 commits into
base: session-3-todo
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions assignment-2/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
FROM golang:1.20 AS builder
WORKDIR /app
COPY . .

FROM alpine:3.13
WORKDIR /app
COPY --from=builder /app/deploy/hacktiv-assignment-2 .
COPY --from=builder /app/template /app/template/.
RUN ls
EXPOSE 8080

ENV APP_NAME=hacktiv-assignment-2
CMD ["./hacktiv-assignment-2"]
34 changes: 34 additions & 0 deletions assignment-2/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
.PHONY: migration
migration:
migrate create -ext sql -dir db/migrations/$(module) $(name)

.PHONY: migrate
migrate:
migrate -path db/migrations/$(module) -database "postgres://postgresuser:postgrespassword@127.0.0.1:5432/postgres?sslmode=disable&search_path=public" -verbose up

.PHONY: rollback
rollback:
migrate -path db/migrations/$(module) -database "postgres://postgresuser:postgrespassword@127.0.0.1:5432/postgres?sslmode=disable&search_path=public" -verbose down 1

.PHONY: rollback-all
rollback-all:
migrate -path db/migrations/$(module) -database "postgres://postgresuser:postgrespassword@127.0.0.1:5432/postgres?sslmode=disable&search_path=public" -verbose down -all

.PHONY: force-migrate
force-migrate:
migrate -path db/migrations/$(module) -database "postgres://postgresuser:postgrespassword@127.0.0.1:5432/postgres?sslmode=disable&search_path=public" -verbose force $(version)

.PHONY: compile-server
compile-server:
GO111MODULE=on CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o deploy/hacktiv-assignment-2 main.go

.PHONY: docker-build-server
docker-build-server:
docker build --no-cache -t hacktiv-assignment-2:latest -f Dockerfile .

.PHONY: run
run:
docker-compose up

.PHONY: compile-build-run
compile-build-run: compile-server docker-build-server run
12 changes: 12 additions & 0 deletions assignment-2/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Assignment 2 Hacktiv
Simple login-logout page with gorilla session stored on postgres db

# Dependencies
- [Docker](https://docs.docker.com/engine/install/ubuntu/)
- [Docker-compose](https://docs.docker.com/compose/install/)

# How To Run
1. Compile server to generate executable file `make compile-server`
2. Build docker image `make docker-build-server`
3. Run docker image `make run`
4. Alternatively, you can use this shortcut to automatically run 3 above steps `make compile-build-run`
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
BEGIN;

DROP TABLE users;

COMMIT;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
BEGIN;

CREATE TABLE users (
id serial not null,
username varchar(50) unique not null,
first_name varchar(200) not null,
last_name varchar(200) not null,
password varchar(120) not null
);

COMMIT;
Binary file added assignment-2/deploy/hacktiv-assignment-2
Binary file not shown.
24 changes: 24 additions & 0 deletions assignment-2/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
version: '3'

services:
postgres:
image: postgres:13.2-alpine
environment:
- POSTGRES_USER=postgresuser
- POSTGRES_PASSWORD=postgrespassword
- POSTGRES_DB=postgres
ports:
- 5432:5432
networks:
- assignment-2
server:
image: hacktiv-assignment-2:latest
ports:
- 8080:8080
depends_on:
- postgres
networks:
- assignment-2

networks:
assignment-2:
11 changes: 11 additions & 0 deletions assignment-2/driver/pgx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package driver

import (
"context"

"github.com/jackc/pgx/v4"
)

func NewPostgresConn(ctx context.Context) (*pgx.Conn, error) {
return pgx.Connect(ctx, POSTGRES_URL)
}
41 changes: 41 additions & 0 deletions assignment-2/driver/renderer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package driver

import (
"html/template"
"io"

"github.com/labstack/echo"
)

type Renderer struct {
template *template.Template
debug bool
location string
}

func NewRenderer(location string, debug bool) *Renderer {
tpl := new(Renderer)
tpl.location = location
tpl.debug = debug

tpl.ReloadTemplates()

return tpl
}

func (t *Renderer) ReloadTemplates() {
t.template = template.Must(template.ParseGlob(t.location))
}

func (t *Renderer) Render(
w io.Writer,
name string,
data interface{},
c echo.Context,
) error {
if t.debug {
t.ReloadTemplates()
}

return t.template.ExecuteTemplate(w, name, data)
}
36 changes: 36 additions & 0 deletions assignment-2/driver/session_store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package driver

import (
"log"

"github.com/antonlindstrom/pgstore"
"github.com/gorilla/sessions"
)

const (
SESSION_ID = "test-id"
POSTGRES_URL = "postgres://postgresuser:postgrespassword@postgres:5432/postgres?sslmode=disable"
)

var (
SESSION_AUTH_KEY = []byte("my-auth-key-very-secret")
SESSION_ENCRYPTION_KEY = []byte("my-encryption-key-very-secret123")
)

func NewPostgresStore() *pgstore.PGStore {
store, err := pgstore.NewPGStore(POSTGRES_URL, SESSION_AUTH_KEY, SESSION_ENCRYPTION_KEY)
if err != nil {
log.Fatalln("ERROR", err)
}

return store
}

func NewCookieStore() *sessions.CookieStore {
store := sessions.NewCookieStore(SESSION_AUTH_KEY, SESSION_ENCRYPTION_KEY)
store.Options.Path = "/"
store.Options.MaxAge = 86400 * 7
store.Options.HttpOnly = true

return store
}
9 changes: 9 additions & 0 deletions assignment-2/entity/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package entity

type User struct {
ID int `json:"id"`
Username string `json:"username"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Password string `json:"password"`
}
21 changes: 21 additions & 0 deletions assignment-2/handler/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package handler

import (
"net/http"

"github.com/antonlindstrom/pgstore"
"github.com/ibrahimker/golang-intermediate/assignment-2/driver"
"github.com/labstack/echo"
)

func storeSessionHelper(c echo.Context, pgs *pgstore.PGStore, username string) error {
session, err := pgs.Get(c.Request(), driver.SESSION_ID)
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
session.Values["username"] = username
if err = session.Save(c.Request(), c.Response()); err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
return nil
}
87 changes: 87 additions & 0 deletions assignment-2/handler/#_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package handler

import (
"net/http"

"github.com/antonlindstrom/pgstore"
"github.com/gorilla/sessions"
"github.com/ibrahimker/golang-intermediate/assignment-2/driver"
"github.com/ibrahimker/golang-intermediate/assignment-2/entity"
"github.com/ibrahimker/golang-intermediate/assignment-2/repository"
"github.com/labstack/echo"
log "github.com/sirupsen/logrus"
)

type HTMLTemplate struct {
User entity.User
Err string
}

type Login struct {
cs *sessions.CookieStore
pgStore *pgstore.PGStore
ur *repository.User
}

func NewLoginHandler(cs *sessions.CookieStore, pgs *pgstore.PGStore, ur *repository.User) *Login {
return &Login{
cs: cs,
pgStore: pgs,
ur: ur,
}
}

func (l *Login) LoginHandler(c echo.Context) error {
log.Info("Start Login Handler")
// authenticate in db
user, err := l.ur.GetByUsernamePassword(c.Request().Context(), c.FormValue("username"), c.FormValue("password"))
if err != nil {
log.Warn(err)
return c.Render(http.StatusOK, "login.html", HTMLTemplate{
User: entity.User{},
Err: "Error when login",
})
}
log.Info("Successfully authenticate user", user)

// store username in session
if err = storeSessionHelper(c, l.pgStore, user.Username); err != nil {
log.Warn("error when store session")
return c.Render(http.StatusOK, "login.html", HTMLTemplate{
User: entity.User{},
Err: "Error when store session",
})
}

return c.Redirect(http.StatusTemporaryRedirect, "/home")
}

func (l *Login) HomeHandler(c echo.Context) error {
log.Info("Start Home Handler")

session, err := l.pgStore.Get(c.Request(), driver.SESSION_ID)
if err != nil {
log.WithError(err).Warn("error when retrieve session")
return c.Redirect(http.StatusTemporaryRedirect, "/#")
}

if len(session.Values) == 0 {
log.Info("no session values available")
return c.Redirect(http.StatusTemporaryRedirect, "/#")
}

log.Info("Session exists, render html")
return c.Render(http.StatusOK, "home.html", HTMLTemplate{
User: entity.User{Username: session.Values["username"].(string)},
Err: "",
})
}

func (l *Login) LogoutHandler(c echo.Context) error {
log.Info("Start Logout Handler")
session, _ := l.pgStore.Get(c.Request(), driver.SESSION_ID)
session.Options.MaxAge = -1
session.Save(c.Request(), c.Response())

return c.Redirect(http.StatusTemporaryRedirect, "/home")
}
51 changes: 51 additions & 0 deletions assignment-2/handler/register_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package handler

import (
"net/http"

"github.com/antonlindstrom/pgstore"
"github.com/gorilla/sessions"
"github.com/ibrahimker/golang-intermediate/assignment-2/entity"
"github.com/ibrahimker/golang-intermediate/assignment-2/repository"
"github.com/labstack/echo"
log "github.com/sirupsen/logrus"
)

type Register struct {
cs *sessions.CookieStore
pgs *pgstore.PGStore
ur *repository.User
}

func NewRegisterHandler(cs *sessions.CookieStore, pgs *pgstore.PGStore, ur *repository.User) *Register {
return &Register{
cs: cs,
pgs: pgs,
ur: ur,
}
}

func (r *Register) RegisterHandler(c echo.Context) error {
data := "Hello from /html"
u := &entity.User{
Username: c.FormValue("username"),
FirstName: c.FormValue("firstname"),
LastName: c.FormValue("lastname"),
Password: c.FormValue("password"),
}
log.Info("user", u)
if u.Username == "" || u.Password == "" {
log.Warn("username password cannot be empty")
return c.Redirect(http.StatusTemporaryRedirect, "/home")
}
if err := r.ur.Insert(c.Request().Context(), u); err != nil {
return c.Render(http.StatusOK, "login.html", data)
}

// store username in session
if err := storeSessionHelper(c, r.pgs, u.Username); err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}

return c.Redirect(http.StatusTemporaryRedirect, "/home")
}
Loading