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

Adding api handler and basic UI #5

Merged
merged 21 commits into from
Aug 23, 2020
Merged
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
40 changes: 33 additions & 7 deletions cmd/dfs/cmd/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,18 @@ func executor(in string) {
return
}
userName := blocks[2]
err := dfsAPI.CreateUser(userName, "")
ref, mnemonic, err := dfsAPI.CreateUser(userName, "")
if err != nil {
fmt.Println("create user: ", err)
return
}
fmt.Println("user created with address ", ref)
fmt.Println("Please store the following 24 words safely")
fmt.Println("if you loose this, you cannot recover the data in-case of an emergency.")
fmt.Println("you can also use this mnemonic to access the data from another device")
fmt.Println("=============== Mnemonic ==========================")
fmt.Println(mnemonic)
fmt.Println("=============== Mnemonic ==========================")
currentUser = userName
currentPodInfo = nil
currentPrompt = getCurrentPrompt()
Expand All @@ -147,7 +154,7 @@ func executor(in string) {
return
}
userName := blocks[2]
err := dfsAPI.DeleteUser(userName)
err := dfsAPI.DeleteUser(userName, "")
if err != nil {
fmt.Println("delete user: ", err)
return
Expand Down Expand Up @@ -294,11 +301,15 @@ func executor(in string) {
fmt.Println("pod synced.")
currentPrompt = getCurrentPrompt()
case "ls":
err := dfsAPI.ListPods(currentUser)
pods, err := dfsAPI.ListPods(currentUser)
if err != nil {
fmt.Println("error while listing pods: %w", err)
return
}
for _, pod := range pods {
fmt.Println(pod)
}
fmt.Println("")
currentPrompt = getCurrentPrompt()
default:
fmt.Println("invalid pod command!!")
Expand All @@ -323,12 +334,15 @@ func executor(in string) {
if !isPodOpened() {
return
}
listing, err := dfsAPI.ListDir(currentUser, currentPodInfo.GetCurrentPodNameOnly())
fl, dl, err := dfsAPI.ListDir(currentUser, currentPodInfo.GetCurrentPodNameOnly(), "")
if err != nil {
fmt.Println("ls failed: ", err)
return
}
for _, l := range listing {
for _, l := range fl {
fmt.Println(l)
}
for _, l := range dl {
fmt.Println(l)
}
case "copyToLocal":
Expand Down Expand Up @@ -404,11 +418,23 @@ func executor(in string) {
fmt.Println("invalid command. Missing one or more arguments")
return
}
err := dfsAPI.DirectoryOrFileStat(currentUser, currentPodInfo.GetCurrentPodNameOnly(), blocks[1])
fs, err := dfsAPI.FileStat(currentUser, currentPodInfo.GetCurrentPodNameOnly(), blocks[1])
if err != nil {
fmt.Println("stat failed: ", err)
return
}
fmt.Println("Account : ", fs.Account)
fmt.Println("PodName : ", fs.PodName)
fmt.Println("File Path : ", fs.FilePath)
fmt.Println("File Name : ", fs.FileName)
fmt.Println("File Size : ", fs.FileSize)
fmt.Println("Cr. Time : ", fs.CreationTime)
fmt.Println("Mo. Time : ", fs.ModificationTime)
fmt.Println("Ac. Time : ", fs.AccessTime)
for _, b := range fs.Blocks {
blkStr := fmt.Sprintf("%s, 0x%s, %s bytes", b.Name, b.Reference, b.Size)
fmt.Println(blkStr)
}
case "pwd":
if !isPodOpened() {
return
Expand All @@ -428,7 +454,7 @@ func executor(in string) {
fmt.Println("invalid command. Missing one or more arguments")
return
}
err := dfsAPI.RemoveFile(currentUser, currentPodInfo.GetCurrentPodNameOnly(), blocks[1])
err := dfsAPI.DeleteFile(currentUser, currentPodInfo.GetCurrentPodNameOnly(), blocks[1])
if err != nil {
fmt.Println("rm failed: ", err)
return
Expand Down
62 changes: 45 additions & 17 deletions cmd/dfs/cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,27 @@ limitations under the License.
package cmd

import (
"log"
"fmt"
"net/http"

"github.com/gorilla/mux"
//"github.com/gorilla/mux"
//"github.com/jmozah/intOS-dfs/pkg/api"
"github.com/spf13/cobra"

"github.com/jmozah/intOS-dfs/pkg/api"
)

var handler *api.Handler

// startCmd represents the start command
var startCmd = &cobra.Command{
Use: "start",
Short: "starts a HTTP server for the dfs",
Long: `Serves all the dfs commands through an HTTP server so that the upper layers
can consume it.`,
Run: func(cmd *cobra.Command, args []string) {
handler = api.NewHandler(dataDir, beeHost, beePort)
startHttpService()
},
}
Expand All @@ -42,20 +47,43 @@ func init() {
}

func startHttpService() {
router := mux.NewRouter().StrictSlash(true)
//router.HandleFunc("/pod/new/{podName}", api.CreatePod).Methods("POST")
//router.HandleFunc("/pod/del/{podName}", api.DeletePod).Methods("DELETE")
//router.HandleFunc("/pod/login/{podName}", api.LoginPod).Methods("POST")
//router.HandleFunc("/pod/logout/{podName}", api.LogoutPod).Methods("POST")
//router.HandleFunc("/pod/ls/{dirName}", api.ListPod).Methods("GET")
//router.HandleFunc("/pod/stat/{fileOrDirName}", api.InfoPod).Methods("GET")
//router.HandleFunc("/pod/sync/{podName}", api.SyncPod).Methods("POST")
//
//router.HandleFunc("/mkdir/{dirName}", api.Mkdir).Methods("POST")
//router.HandleFunc("/rmdir/{dirName}", api.Rmdir).Methods("DELETE")
//router.HandleFunc("/copyFromLocal/", api.CopyFromLocal).Methods("POST")
//router.HandleFunc("/copyToLocal/", api.CopyToLocal).Methods("POST")
//router.HandleFunc("/rm/{fileName}", api.RemoveFile).Methods("DELETE")

log.Fatal(http.ListenAndServe("127.0.0.1:"+httpPort, router))
router := mux.NewRouter()

// User account related handlers
router.HandleFunc("/v0/user/signup", handler.UserSignupHandler).Methods("POST")
router.HandleFunc("/v0/user/delete", handler.UserDeleteHandler).Methods("POST")
router.HandleFunc("/v0/user/login", handler.UserLoginHandler).Methods("POST")
router.HandleFunc("/v0/user/logout", handler.UserLogoutHandler).Methods("POST")
router.HandleFunc("/v0/user/present", handler.UserPresentHandler).Methods("POST")

// pod related handlers
router.HandleFunc("/v0/pod/new", handler.PodCreateHandler).Methods("POST")
router.HandleFunc("/v0/pod/delete", handler.PodDeleteHandler).Methods("POST")
router.HandleFunc("/v0/pod/open", handler.PodOpenHandler).Methods("POST")
router.HandleFunc("/v0/pod/close", handler.PodCloseHandler).Methods("POST")
router.HandleFunc("/v0/pod/ls", handler.PodListHandler).Methods("POST")
router.HandleFunc("/v0/pod/stat", handler.PodStatHandler).Methods("POST")
router.HandleFunc("/v0/pod/sync", handler.PodSyncHandler).Methods("POST")

// directory related handlers
router.HandleFunc("/v0/dir/mkdir", handler.DirectoryMkdirHandler).Methods("POST")
router.HandleFunc("/v0/dir/rmdir", handler.DirectoryRmdirHandler).Methods("POST")
router.HandleFunc("/v0/dir/ls", handler.DirectoryLsHandler).Methods("POST")
router.HandleFunc("/v0/dir/stat", handler.DirectoryStatHandler).Methods("POST")

// file related handlers
router.HandleFunc("/v0/file/download", handler.FileDownloadHandler).Methods("POST")
router.HandleFunc("/v0/file/upload", handler.FileUploadHandler).Methods("POST")
router.HandleFunc("/v0/file/stat", handler.FileStatHandler).Methods("POST")
router.HandleFunc("/v0/file/delete", handler.FileDeleteHandler).Methods("POST")

http.Handle("/", router)

fmt.Println("listening on port:", httpPort)
err := http.ListenAndServe(":"+httpPort, nil)
if err != nil {
fmt.Println("listenAndServe: %w", err)
return
}

}
1 change: 1 addition & 0 deletions cmd/dfs/cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package cmd

import (
"fmt"

"github.com/spf13/cobra"
)

Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.14
require (
github.com/FactomProject/basen v0.0.0-20150613233007-fe3947df716e // indirect
github.com/FactomProject/btcutilecc v0.0.0-20130527213604-d3a63a5752ec // indirect
github.com/btcsuite/btcd v0.20.1-beta
github.com/btcsuite/btcd v0.20.1-beta // indirect
github.com/c-bata/go-prompt v0.2.3
github.com/dustin/go-humanize v1.0.0
github.com/ethereum/go-ethereum v1.9.5
Expand All @@ -26,5 +26,6 @@ require (
github.com/vishvananda/netlink v1.0.0 // indirect
github.com/vishvananda/netns v0.0.0-20190625233234-7109fa855b0f // indirect
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9
resenje.org/jsonhttp v0.2.0
resenje.org/jsonresponse v0.1.2 // indirect
)
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -1272,6 +1272,7 @@ k8s.io/utils v0.0.0-20190607212802-c55fbcfc754a/go.mod h1:sZAwmy6armz5eXlNoLmJcl
resenje.org/daemon v0.1.2/go.mod h1:mF5JRpH3EbrxI9WoeKY78e6PqSsbBtX9jAQL5vj/GBA=
resenje.org/email v0.1.2/go.mod h1:erp4uyQKjfJMEKrlG6JIWbMhFlUpIV+pkFptfJNm5uA=
resenje.org/email v0.1.3/go.mod h1:OhAVLRG3vqd9NSgayN3pAgzxTmc2B6mAefgShZvEgf0=
resenje.org/jsonhttp v0.2.0 h1:muOrhvgScixgVKAlYFcB8CKNxH95gnsqrf61P0Mpze0=
resenje.org/jsonhttp v0.2.0/go.mod h1:EDyeguyTWj2fU3D3SCE0qNTgthzyEkHYLM1uu0uikHU=
resenje.org/jsonresponse v0.1.2/go.mod h1:L+alM0Xnew+XnpuINkpoyJI8Q6zaVKqmGkW8ELwzxs0=
resenje.org/logging v0.1.5/go.mod h1:1IdoCm3+UwYfsplxDGV2pHCkUrLlQzlWwp4r28XfPx4=
Expand Down
87 changes: 59 additions & 28 deletions pkg/account/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/ethersphere/bee/pkg/crypto"
"github.com/jmozah/intOS-dfs/pkg/utils"
hdwallet "github.com/miguelmota/go-ethereum-hdwallet"
"github.com/tyler-smith/go-bip39"
"golang.org/x/crypto/ssh/terminal"
)

Expand Down Expand Up @@ -77,39 +78,45 @@ func (a *Account) IsAlreadyInitialized() bool {
return !info.IsDir()
}

func (a *Account) CreateUserAccount(passPhrase string) error {
if a.IsAlreadyInitialized() {
var s string
fmt.Println("user is already initialised")
fmt.Println("reinitialising again will make all the your data inaccessible")
fmt.Printf("do you still want to proceed (Y/N):")
_, err := fmt.Scan(&s)
if err != nil {
return err
}

s = strings.TrimSpace(s)
s = strings.ToLower(s)
s = strings.Trim(s, "\n")

if s == "n" || s == "no" {
return nil
func (a *Account) CreateUserAccount(passPhrase string) (string, error) {
if passPhrase == "" {
if a.IsAlreadyInitialized() {
var s string
fmt.Println("user is already initialised")
fmt.Println("reinitialising again will make all the your data inaccessible")
fmt.Printf("do you still want to proceed (Y/N):")
_, err := fmt.Scan(&s)
if err != nil {
return "", err
}

s = strings.TrimSpace(s)
s = strings.ToLower(s)
s = strings.Trim(s, "\n")

if s == "n" || s == "no" {
return "", nil
}
err = os.Remove(a.mnemonicFileName)
if err != nil {
return "", fmt.Errorf("could not remove user key: %w", err)
}
}
err = os.Remove(a.mnemonicFileName)
if err != nil {
return fmt.Errorf("could not remove user key: %w", err)
} else {
if a.IsAlreadyInitialized() {
return "", fmt.Errorf("user already present")
}
}

wallet := NewWallet("")
a.wallet = wallet
acc, mnemonic, err := wallet.LoadMnemonicAndCreateRootAccount()
if err != nil {
return err
return "", err
}

if passPhrase == "" {
fmt.Println("Please store the following 24 words safely")
fmt.Println("Please store the following 12 words safely")
fmt.Println("if can use this to import the wallet in another machine")
fmt.Println("=============== Mnemonic ==========================")
fmt.Println(mnemonic)
Expand All @@ -118,31 +125,32 @@ func (a *Account) CreateUserAccount(passPhrase string) error {

hdw, err := hdwallet.NewFromMnemonic(mnemonic)
if err != nil {
return err
return "", err
}

// store publicKey, private key and user
a.userAcount.privateKey, err = hdw.PrivateKey(acc)
if err != nil {
return err
return "", err
}
a.userAcount.publicKey, err = hdw.PublicKey(acc)
if err != nil {
return err
return "", err
}
addrBytes, err := crypto.NewEthereumAddress(a.userAcount.privateKey.PublicKey)
if err != nil {
return err
return "", err
}
a.userAcount.address.SetBytes(addrBytes)

// store the mnemonic
encryptedMnemonic, err := a.storeAsEncryptedMnemonicToDisk(mnemonic, passPhrase)
if err != nil {
return err
return "", err
}
a.wallet.encryptedmnemonic = encryptedMnemonic
return nil

return mnemonic, nil
}

func (a *Account) LoadUserAccount(passPhrase string) error {
Expand Down Expand Up @@ -187,6 +195,29 @@ func (a *Account) LoadUserAccount(passPhrase string) error {
return nil
}

func (a *Account) Authorise(password string) bool {
if password == "" {
fmt.Print("Enter user password to create a pod: ")
password = a.getPassword()
}
plainMnemonic, err := a.wallet.decryptMnemonic(password)
if err != nil {
return false
}
// check the validity of the mnemonic
if plainMnemonic == "" {
return false
}
words := strings.Split(plainMnemonic, " ")
if len(words) != 12 {
return false
}
if !bip39.IsMnemonicValid(plainMnemonic) {
return false
}
return true
}

func (a *Account) CreatePodAccount(accountId int, passPhrase string) error {
if !a.IsAlreadyInitialized() {
return fmt.Errorf("user not created")
Expand Down
8 changes: 4 additions & 4 deletions pkg/account/account_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestAccount_CreateRootAccount(t *testing.T) {
podName := "test_pod1"
password := "letmein"
acc := New(podName, tempDir)
err = acc.CreateUserAccount(password)
_, err = acc.CreateUserAccount(password)
if err != nil {
t.Fatal(err)
}
Expand All @@ -49,8 +49,8 @@ func TestAccount_CreateRootAccount(t *testing.T) {
}

words := strings.Split(plainMnemonic, " ")
if len(words) != 24 {
t.Fatal("mnemonic is not 24 words")
if len(words) != 12 {
t.Fatal("mnemonic is not 12 words")
}

if !acc.IsAlreadyInitialized() {
Expand All @@ -75,7 +75,7 @@ func TestLoadAndStoreMnemonic(t *testing.T) {
podName := "test_pod1"
password := "letmein"
acc := New(podName, tempDir)
err = acc.CreateUserAccount(password)
_, err = acc.CreateUserAccount(password)
if err != nil {
t.Fatal(err)
}
Expand Down
Loading