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

Added docker compose and removed redux #3

Open
wants to merge 2 commits into
base: master
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
node_modules/
.env.development
.env
build/
.vscode/
3 changes: 0 additions & 3 deletions .vscode/settings.json

This file was deleted.

2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ WORKDIR /server

COPY --from=react-build /app/build build/

COPY main.go go.mod go.sum ./
COPY main.go tokenHandler.go go.mod go.sum ./

RUN go mod download

Expand Down
8 changes: 8 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
version: '3'
services:
web:
build: .
ports:
- "3000:3000"
env_file:
- ./.env
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4=
github.com/gin-contrib/sse v0.0.0-20170109093832-22d885f9ecc7 h1:AzN37oI0cOS+cougNAV9szl6CVoj2RYwzS3DpUQNtlY=
Expand All @@ -13,10 +14,13 @@ github.com/mattn/go-isatty v0.0.4 h1:bnP0vzxcAdeI1zdubAl5PjU6zsERjGZb7raWodagDYs
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/ugorji/go/codec v0.0.0-20181209151446-772ced7fd4c2 h1:EICbibRW4JNKMcY+LsWmuwob+CRS1BmdRdjphAm9mH4=
github.com/ugorji/go/codec v0.0.0-20181209151446-772ced7fd4c2/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3 h1:eH6Eip3UpmR+yM/qI9Ijluzb1bNv/cAU/n+6l8tRSis=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20181221143128-b4a75ba826a6/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand Down
18 changes: 13 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
package main

import (
"fmt"
"os"

"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
)

func noRouteHandler(c *gin.Context) {
c.File("./build/index.html")
}

func main() {
fmt.Printf("Client id -> %s", os.Getenv("CLIENT_ID"))
r := gin.Default()

r.Use(static.Serve("/", static.LocalFile("build/", false)))
r.GET("/ping", func(c *gin.Context) {
c.String(200, "test")
})
r.Use(static.Serve("/", static.LocalFile("./build", true)))
api := r.Group("/api")
api.POST("/generate_token", tokenHandler)
r.NoRoute(noRouteHandler)

r.Run(":8080")
r.Run(":3000")
}
3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,11 @@
"@types/react-dom": "16.8.3",
"@types/react-router": "^4.4.5",
"@types/react-router-dom": "^4.3.2",
"@types/redux": "^3.6.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-router": "^5.0.0",
"react-router-dom": "^5.0.0",
"react-scripts": "2.1.8",
"redux": "^4.0.1",
"redux-react-hook": "^3.3.1",
"typescript": "3.4.2"
},
"scripts": {
Expand Down
15 changes: 6 additions & 9 deletions src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { StoreContext } from 'redux-react-hook';
import Login from './Login'
import Home from './Home'
import Redirect from './Redirect'
import { makeStore } from './store';

const App = () => {
const store = makeStore();
return (
<StoreContext.Provider value={store}>
<Router>
<Router>
<div>
<Route path="/" exact component={Login} />
<Route path="/login-success" exact component={Redirect} />
<Route path="/home" exact component={Home} />
</Router>
</StoreContext.Provider>
<Route path="/login-success" component={Redirect} />
<Route path="/home" component={Home} />
</div>
</Router>
);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const Login = () => {

const openPopup = () => {
const url = 'https://www.reddit.com/api/v1/authorize' +
`?client_id=CLIENT_ID` +
`?client_id=YdNu-wlTwwHI6A` +
`&response_type=code` +
`&state=${new Date().valueOf().toString()}` +
`&redirect_uri=http://localhost:3000/login-success` +
Expand Down
8 changes: 2 additions & 6 deletions src/Redirect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,9 @@ const LoginSuccess = (props: any) => {
useEffect(() => {
let params = new URLSearchParams(props.location.search)
const authToken = params.get('code')
fetch(`https://www.reddit.com/api/v1/access_token?grant_type=authorization_code&code=${authToken}&redirect_uri=http://localhost:3000/login-success`, {
fetch(`/api/generate_token`, {
method: 'POST',
// mode: "no-cors",
// body: `grant_type=authorization_code&code=${authToken}&redirect_uri=http://localhost:3000/login-success`,
headers: {
Authorization: `Basic ${btoa('CLIENT_ID:CLIENT_SECRET')}`
}
body: JSON.stringify({ code: authToken })
})
.then(res => res.json())
.then((response) => {
Expand Down
10 changes: 1 addition & 9 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,5 @@ import ReactDOM from "react-dom";
import Application from './App';
import "./styles.css";

function App() {
return (
<div className="App">
<Application />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
ReactDOM.render(<Application />, rootElement);
26 changes: 0 additions & 26 deletions src/reducer.ts

This file was deleted.

22 changes: 0 additions & 22 deletions src/store.ts

This file was deleted.

67 changes: 67 additions & 0 deletions tokenHandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package main

import (
"bytes"
"encoding/base64"
"encoding/json"
"net/http"
"net/url"
"os"
"strings"

"github.com/gin-gonic/gin"
)

type tokenRequestParams struct {
Code string `json:"code"`
}

func tokenHandler(c *gin.Context) {
var reqParams tokenRequestParams

if err := c.ShouldBindJSON(&reqParams); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

client := &http.Client{}
data := url.Values{}
redirectURL := "http://localhost:3000/login-success"
data.Set("grant_type", "authorization_code")
data.Add("code", reqParams.Code)
data.Add("redirect_uri", redirectURL)
u, _ := url.ParseRequestURI("https://www.reddit.com")
u.Path = "/api/v1/access_token/"
urlString := u.String()
req, e := http.NewRequest("POST", urlString, bytes.NewBufferString(data.Encode()))

if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": e})
}

authValue := strings.Join([]string{os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET")}, ":")
basicToken := strings.Join([]string{"Basic", base64.StdEncoding.EncodeToString([]byte(authValue))}, " ")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
req.Header.Set("Authorization", basicToken)
req.Header.Set("User-Agent", "leerlo v0.0.1 (by /u/aravind741)")
res, e := client.Do(req)
if e != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": e})
}

if res.StatusCode != http.StatusOK {
c.JSON(http.StatusUnauthorized, gin.H{})
}

var result map[string]interface{}
json.NewDecoder(res.Body).Decode(&result)

if result["access_token"] == nil {
c.JSON(http.StatusUnauthorized, gin.H{})
} else {
c.JSON(http.StatusOK, gin.H{
"access_token": result["access_token"],
"refresh_token": result["refresh_token"],
})
}
}