Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
docs: example showing how to handle user identity (#54)
* docs: example showing how to handle user identity An simple example showing how to handle user identity. Signed-off-by: Carlos A Becker <caarlos0@users.noreply.github.com> * fix: use ssh.KeysEqual Co-authored-by: Ayman Bagabas <ayman.bagabas@gmail.com>
- Loading branch information
1 parent
c27ea5f
commit 45089b6
Showing
2 changed files
with
69 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package main | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"log" | ||
"os" | ||
"os/signal" | ||
"syscall" | ||
"time" | ||
|
||
"github.com/charmbracelet/wish" | ||
"github.com/charmbracelet/wish/logging" | ||
"github.com/gliderlabs/ssh" | ||
) | ||
|
||
const ( | ||
host = "localhost" | ||
port = 23234 | ||
) | ||
|
||
func main() { | ||
s, err := wish.NewServer( | ||
wish.WithAddress(fmt.Sprintf("%s:%d", host, port)), | ||
wish.WithHostKeyPath(".ssh/term_info_ed25519"), | ||
wish.WithPublicKeyAuth(func(ctx ssh.Context, key ssh.PublicKey) bool { | ||
return true | ||
}), | ||
wish.WithMiddleware( | ||
logging.Middleware(), | ||
func(h ssh.Handler) ssh.Handler { | ||
return func(s ssh.Session) { | ||
carlos, _, _, _, _ := ssh.ParseAuthorizedKey( | ||
[]byte("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILxWe2rXKoiO6W14LYPVfJKzRfJ1f3Jhzxrgjc/D4tU7"), | ||
) | ||
switch { | ||
case ssh.KeysEqual(s.PublicKey(), carlos): | ||
wish.Println(s, "Hey Carlos!") | ||
default: | ||
wish.Println(s, "Hey, I don't know who you are!") | ||
} | ||
h(s) | ||
} | ||
}, | ||
), | ||
) | ||
if err != nil { | ||
log.Fatalln(err) | ||
} | ||
|
||
done := make(chan os.Signal, 1) | ||
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) | ||
log.Printf("Starting SSH server on %s:%d", host, port) | ||
go func() { | ||
if err = s.ListenAndServe(); err != nil { | ||
log.Fatalln(err) | ||
} | ||
}() | ||
|
||
<-done | ||
log.Println("Stopping SSH server") | ||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) | ||
defer func() { cancel() }() | ||
if err := s.Shutdown(ctx); err != nil { | ||
log.Fatalln(err) | ||
} | ||
} |