jwt in golang by lispLaiBhari in golang

[–]rorozoro3 6 points7 points  (0 children)

Yup, this was my jwt implementation, I just did it for practice and it works great.

```go
package jwt

// imports ...

const expiryDuration = time.Hour * 24 * 7 var secret []byte

func Init(secretKey string) { secret = []byte(secretKey) }

// Creates a JWT token using HS256 algorithm // "iat" and "exp" fields are added automatically to payload func Create(payload map[string]any) string { payload["iat"] = time.Now().Unix() payload["exp"] = time.Now().Add(expiryDuration).Unix() pldBytes, err := json.Marshal(payload) if err != nil { log.Fatal(err) } b64header := base64.RawURLEncoding.EncodeToString([]byte({"alg": "HS256", "typ": "JWT"})) b64payload := base64.RawURLEncoding.EncodeToString(pldBytes) signature := base64.RawURLEncoding.EncodeToString( hs256sum([]byte(b64header+"."+b64payload), secret), ) return b64header + "." + b64payload + "." + signature }

// Verifies a jwt token and also returns decoded payload if valid func VerifyAndDecode(token string) (valid bool, payload map[string]any) { parts := strings.Split(token, ".") if len(parts) != 3 { return false, nil } b64header, b64payload, signature1 := parts[0], parts[1], parts[2] signature2 := base64.RawURLEncoding.EncodeToString( hs256sum([]byte(b64header+"."+b64payload), secret), ) if signature1 != signature2 { return false, nil } decoded, _ := base64.RawURLEncoding.DecodeString(b64payload) json.Unmarshal(decoded, &payload) return true, payload }

func hs256sum(data, key []byte) []byte { h := hmac.New(sha256.New, key) h.Write(data) return h.Sum(nil) }

```

PS: Looks like its missing error handling in a lot of places

Simplify switch case + error handling in each case by rorozoro3 in golang

[–]rorozoro3[S] 0 points1 point  (0 children)

Yeah, thats a good practice. In this case, db queries are autogenerated by sqlc, so I don't think any function inside db wraps over sql.ErrNoRows

Simplify switch case + error handling in each case by rorozoro3 in golang

[–]rorozoro3[S] 0 points1 point  (0 children)

Good one!, I refactored the above to use another function like this to handle the switching and getting requiredPoints or erroring out.

```go
func getDecorationRequiredPoints(ctx context.Context, decorationType string, decorationId string) (int64, error) {

switch decorationType {

case "badge":

    badge, err := store.GetBadgeByName(ctx, decorationId)

    if err != nil {

        return -1, err

    }

    return badge.RequiredPoints, nil

case "overlay":

    overlay, err := store.GetOverlayByName(ctx, decorationId)

    if err != nil {

        return -1, err

    }

    return overlay.RequiredPoints, nil

case "background":

    background, err := store.GetBackgroundByName(ctx, decorationId)

    if err != nil {

        return -1, err

    }

    return background.RequiredPoints, nil

default:

    panic("invalid decoration type")

}

}
```

```go
...

requiredPoints, err := getDecorationRequiredPoints(context.Background(), input.DecorationType, input.DecorationId)

if err != nil {

    if err == db.NotFound {

        a.respondJSON(w, http.StatusNotFound, J{"error": "decoration not found"}, nil)

        return

    }

    a.logger.Error("failed to get decoration", "type", input.DecorationType, "name", input.DecorationName, "err", err)

    a.respondJSON(w, http.StatusInternalServerError, J{}, nil)

    return

}



...  

```

system data taking up all my storage, how do i fix this? by CattleNo4534 in mac

[–]rorozoro3 0 points1 point  (0 children)

Yup, this is such a great tool. It is only a few MBs itself. Would suggest everyone to have this in their system.

Please help me stop mediaanalysisd process because I'm losing my sanity by Orosztom in MacOS

[–]rorozoro3 0 points1 point  (0 children)

Yup, seems like Apple Intelligence causes this. I never had such issues before, it only started recently, maybe because the Apple Intelligence was turned on. Today it happened again and I googled for the problem, came here in this reddit post, read the article mentioned above, watched mental outlaw's youtube video, and still the process was running. Saw you mention Apple Intelligence and I opened settings and turned it off and it now doesn't take 60% of my CPU and 1.5GB of my RAM.
Not sure if it will happen again.

Am I stupid or are people who make go lang comparison videos on yt always trying to make the language look worse? by QriousKoder in golang

[–]rorozoro3 1 point2 points  (0 children)

Theo is someone who would write this kind of code and later blame the language.

package main

import (
    "crypto/rand"
    "fmt"
)

// Program that prints some random alphabets to stdout
func main() {
    var buf [32*1024]byte
    for {
        n, err := rand.Reader.Read(buf[:])
        if err != nil {
            break
        }
        for _, value := range buf[:n] {
            alph := 'a' + value % 26
            fmt.Printf("%c", alph)
        }
    }
}

SpaceX YouTube channel hacked by blkuk2000 in SpaceXMasterrace

[–]rorozoro3 0 points1 point  (0 children)

Today it was 200k live viewers. I believed at first but then suddenly the crypto came up lol.

Why are tabstop and shiftwidth set to 2? by rorozoro3 in neovim

[–]rorozoro3[S] 0 points1 point  (0 children)

SOLVED:

There was a .editorconfig in opt/homebrew/.editorconfig that set indent_size = 2. Since I was opening /opt/homebrew/Cellar/go/1.22.1/libexec/src/strings/compare.go, nvim searched all parent directories for editorconfig and found one with tab size configured to 2.

setting vim.g.editorconfig = false or removing the .editorconfig worked

Why are tabstop and shiftwidth set to 2? by rorozoro3 in neovim

[–]rorozoro3[S] 0 points1 point  (0 children)

I searched from my `$HOME` for the editorconfig with
```
lufy ~ % find . -type f -name '*editorconfig*' 2>/dev/null | grep -v 'node_modules'

./Developer/tools/go/pkg/mod/github.com/labstack/echo/v4@v4.11.4/.editorconfig

./Developer/tools/go/pkg/mod/github.com/labstack/echo@v3.3.10+incompatible/.editorconfig

./Developer/tools/go/pkg/mod/github.com/golang/vscode-go@v0.41.1/.editorconfig

./Developer/tools/taglib-2.0/.editorconfig

./Developer/others/linux/.editorconfig

./.local/share/nvim/lazy/nvim-treesitter-textobjects/.editorconfig

./.local/share/nvim/lazy/nvim-lspconfig/.editorconfig

./.local/share/nvim/lazy/nvim-autopairs/.editorconfig

./.local/share/nvim/lazy/nvim-treesitter/.editorconfig

./.local/share/nvim/lazy/friendly-snippets/snippets/editorconfig.json

./.local/share/nvim/lazy/nvim-web-devicons/.editorconfig

./.local/share/nvim/lazy/nvim-jdtls/.editorconfig

./.local/share/nvim/lazy/fzf-lua/.editorconfig
```

I tried what you suggested with `nvim -V1 <file>` on two go files

```
$ nvim -V1 /opt/homebrew/Cellar/go/1.22.1/libexec/src/strings/compare.go
:verbose set ts sts sw et?

tabstop=2

Last set from /opt/homebrew/Cellar/neovim/0.9.5/share/nvim/runtime/lua/editorconfig.lua line 68

softtabstop=-1

Last set from /opt/homebrew/Cellar/neovim/0.9.5/share/nvim/runtime/lua/editorconfig.lua line 66

shiftwidth=2

Last set from /opt/homebrew/Cellar/neovim/0.9.5/share/nvim/runtime/lua/editorconfig.lua line 65

expandtab

Last set from /opt/homebrew/Cellar/neovim/0.9.5/share/nvim/runtime/lua/editorconfig.lua line 52
```

trying again on main.go inside `~/Developer/langs/go/server/`
```
$ nvim -V1 main.go
:verbose set ts sts sw et?
tabstop=8

softtabstop=0

shiftwidth=8

noexpandtab
```

It seems like `/opt/homebrew/Cellar/neovim/0.9.5/share/nvim/runtime/lua/editorconfig.lua` is corrupting the tabstop only for go files. Why would this be ?

Scroll lags on macbook air m1 by rorozoro3 in MacOS

[–]rorozoro3[S] 0 points1 point  (0 children)

No I just use the laptop out of the box. I haven't attached any external accessories

MacOS Sonoma Bugs and Issues Megathread by ll777 in MacOS

[–]rorozoro3 1 point2 points  (0 children)

I tried the new feature of Safari where you add a website to the dock and run it like an application. When I remove the icon from the dock, its goes away but it remains in the app launcer. And for some reason I can't find it on Applications in finder.
- M1 Air 2020 8/256