Skip to content

Commit

Permalink
Add en/0.6.x.md syntax highlighting
Browse files Browse the repository at this point in the history
  • Loading branch information
vcaesar committed May 20, 2017
1 parent 919364c commit 19c6592
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 45 deletions.
20 changes: 10 additions & 10 deletions en/06.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ If your application does set an expiry time (for example, setMaxAge(60*60*24)),
## Set cookies in Go

Go uses the `SetCookie` function in the `net/http` package to set cookies:

```Go
http.SetCookie(w ResponseWriter, cookie *Cookie)

```
`w` is the response of the request and cookie is a struct. Let's see what it looks like:

```Go
type Cookie struct {
Name string
Value string
Expand All @@ -57,27 +57,27 @@ Go uses the `SetCookie` function in the `net/http` package to set cookies:
Raw string
Unparsed []string // Raw text of unparsed attribute-value pairs
}

```
Here is an example of setting a cookie:

```Go
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
http.SetCookie(w, &cookie)

```  
## Fetch cookies in Go
The above example shows how to set a cookie. Now let's see how to get a cookie that has been set:

```Go
cookie, _ := r.Cookie("username")
fmt.Fprint(w, cookie)

```
Here is another way to get a cookie:

```Go
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}

```
As you can see, it's very convenient to get cookies from requests.

## Sessions
Expand Down
46 changes: 23 additions & 23 deletions en/06.2.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Next, we'll examine a complete example of a Go session manager and the rationale
### Session manager

Define a global session manager:

```Go
type Manager struct {
cookieName string //private cookiename
lock sync.Mutex // protects session
Expand All @@ -49,40 +49,40 @@ Define a global session manager:
}
return &Manager{provider: provider, cookieName: cookieName, maxlifetime: maxlifetime}, nil
}

```
Create a global session manager in the `main()` function:

```Go
var globalSessions *session.Manager
// Then, initialize the session manager
func init() {
globalSessions = NewManager("memory","gosessionid",3600)
}

```
We know that we can save sessions in many ways including in memory, the file system or directly into the database. We need to define a `Provider` interface in order to represent the underlying structure of our session manager:

```Go
type Provider interface {
SessionInit(sid string) (Session, error)
SessionRead(sid string) (Session, error)
SessionDestroy(sid string) error
SessionGC(maxLifeTime int64)
}

```
- `SessionInit` implements the initialization of a session, and returns a new session if it succeeds.
- `SessionRead` returns a session represented by the corresponding sid. Creates a new session and returns it if it does not already exist.
- `SessionDestroy` given an sid, deletes the corresponding session.
- `SessionGC` deletes expired session variables according to `maxLifeTime`.

So what methods should our session interface have? If you have any experience in web development, you should know that there are only four operations for sessions: set value, get value, delete value and get current session id. So, our session interface should have four methods to perform these operations.

```Go
type Session interface {
Set(key, value interface{}) error //set session value
Get(key interface{}) interface{} //get session value
Delete(key interface{}) error //delete session value
SessionID() string //back current sessionID
}

```
This design takes its roots from the `database/sql/driver`, which defines the interface first, then registers specific structures when we want to use it. The following code is the internal implementation of a session register function.

```Go
var provides = make(map[string]Provider)

// Register makes a session provider available by the provided name.
Expand All @@ -97,23 +97,23 @@ This design takes its roots from the `database/sql/driver`, which defines the in
}
provides[name] = provider
}

```
### Unique session id's

Session id's are for identifying users of web applications, so they must be unique. The following code shows how to achieve this goal:

```Go
func (manager *Manager) sessionId() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(b)
}

```
### Creating a session

We need to allocate or get an existing session in order to validate user operations. The `SessionStart` function is for checking the existence of any sessions related to the current user, and creating a new session if none is found.

```Go
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
manager.lock.Lock()
defer manager.lock.Unlock()
Expand All @@ -129,9 +129,9 @@ We need to allocate or get an existing session in order to validate user operati
}
return
}

```
Here is an example that uses sessions for a login operation.

```Go
func login(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
r.ParseForm()
Expand All @@ -144,13 +144,13 @@ Here is an example that uses sessions for a login operation.
http.Redirect(w, r, "/", 302)
}
}

```
### Operation value: set, get and delete

The `SessionStart` function returns a variable that implements a session interface. How do we use it?

You saw `session.Get("uid")` in the above example for a basic operation. Now let's examine a more detailed example.

```Go
func count(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
createtime := sess.Get("createtime")
Expand All @@ -170,16 +170,16 @@ You saw `session.Get("uid")` in the above example for a basic operation. Now let
w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("countnum"))
}

```
As you can see, operating on sessions simply involves using the key/value pattern in the Set, Get and Delete operations.

Because sessions have the concept of an expiry time, we define the GC to update the session's latest modify time. This way, the GC will not delete sessions that have expired but are still being used.

### Reset sessions

We know that web applications have a logout operation. When users logout, we need to delete the corresponding session. We've already used the reset operation in above example -now let's take a look at the function body.

//Destroy sessionid
```Go
// Destroy sessionid
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request){
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
Expand All @@ -193,11 +193,11 @@ We know that web applications have a logout operation. When users logout, we nee
http.SetCookie(w, &cookie)
}
}

```
### Delete sessions

Let's see how to let the session manager delete a session. We need to start the GC in the `main()` function:

```Go
func init() {
go globalSessions.GC()
}
Expand All @@ -208,7 +208,7 @@ Let's see how to let the session manager delete a session. We need to start the
manager.provider.SessionGC(manager.maxlifetime)
time.AfterFunc(time.Duration(manager.maxlifetime), func() { manager.GC() })
}

```
We see that the GC makes full use of the timer function in the `time` package. It automatically calls GC when the session times out, ensuring that all sessions are usable during `maxLifeTime`. A similar solution can be used to count online users.

## Summary
Expand Down
12 changes: 6 additions & 6 deletions en/06.3.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 6.3 Session storage

We introduced a simple session manager's working principles in the previous section, and among other things, we defined a session storage interface. In this section, I'm going to show you an example of a memory based session storage engine that implements this interface. You can tailor this to other forms of session storage as well.

```Go
package memory

import (
Expand Down Expand Up @@ -114,24 +114,24 @@ We introduced a simple session manager's working principles in the previous sect
session.Register("memory", pder)
}


```
The above example implements a memory based session storage mechanism. It uses its `init()` function to register this storage engine to the session manager. So how do we register this engine from our main program?

```Go
import (
"github.com/astaxie/session"
_ "github.com/astaxie/session/providers/memory"
)

```
We use the blank import mechanism (which will invoke the package's `init()` function automatically) to register this engine to a session manager. We then use the following code to initialize the session manager:

```Go
var globalSessions *session.Manager

// initialize in init() function
func init() {
globalSessions, _ = session.NewManager("memory", "gosessionid", 3600)
go globalSessions.GC()
}

```
## Links

- [Directory](preface.md)
Expand Down
12 changes: 6 additions & 6 deletions en/06.4.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ In this section, we are going to show you how to hijack a session for educationa
## The session hijacking process

The following code is a counter for the `count` variable:

```Go
func count(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
ct := sess.Get("countnum")
Expand All @@ -20,7 +20,7 @@ The following code is a counter for the `count` variable:
w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("countnum"))
}

```
The content of `count.gtpl` is as follows:

Hi. Now count:{{.}}
Expand Down Expand Up @@ -60,7 +60,7 @@ Through this simple example of hijacking a session, you can see that it's very d
The first step is to only set session id's in cookies, instead of in URL rewrites. Also, we should set the httponly cookie property to true. This restricts client-side scripts from gaining access to the session id. Using these techniques, cookies cannot be accessed by XSS and it won't be as easy as we demonstrated to get a session id from a cookie manager.

The second step is to add a token to every request. Similar to the manner in which we dealt with repeating form submissions in previous sections, we add a hidden field that contains a token. When a request is sent to the server, we can verify this token to prove that the request is unique.

```Go
h := md5.New()
salt:="astaxie%^7&8888"
io.WriteString(h,salt+time.Now().String())
Expand All @@ -69,19 +69,19 @@ The second step is to add a token to every request. Similar to the manner in whi
// ask to log in
}
sess.Set("token",token)

```
### Session id timeout

Another solution is to add a create time for every session, and to replace expired session id's with new ones. This can prevent session hijacking under certain circumstances such as when the hijack is attempted too late.

```Go
createtime := sess.Get("createtime")
if createtime == nil {
sess.Set("createtime", time.Now().Unix())
} else if (createtime.(int64) + 60) < (time.Now().Unix()) {
globalSessions.SessionDestroy(w, r)
sess = globalSessions.SessionStart(w, r)
}

```
We set a value to save the create time and check if it's expired (I set 60 seconds here). This step can often thwart session hijacking attempts.

By combining the two solutions set out above you will be able to prevent most session hijacking attempts from succeeding. On the one hand, session id's that are frequently reset will result in an attacker always getting expired and useless session id's; on the other hand, by setting the httponly property on cookies and ensuring that session id's can only be passed via cookies, all URL based attacks are mitigated. Finally, we set `MaxAge=0` on our cookies, which means that the session id's will not be saved in the browser history.
Expand Down

0 comments on commit 19c6592

Please sign in to comment.