commit e26324c07ed58c3d7a44a6dce9d27ab5cdcf5693 Author: Mysh! Date: Sun Feb 12 23:44:50 2023 +0300 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..d80b990 --- /dev/null +++ b/README.md @@ -0,0 +1,56 @@ +![Maddy password reset service logo](https://user-images.githubusercontent.com/44648612/218335570-cdb3ba2f-4ff9-43ee-bd43-f892c644b153.png) + +# Maddy password reset service + +Runs an HTTP server that serves password reset form. + +Still Work In Progress! + +## Installation + +For the time being, you have to compile it yourself. +In the future there will be prebuilt binaries. + +### Requirements + +- Go +- Maddy + +To build this project install `Go` and execute this: +```shell +go build ./main.go +``` + +Make sure to configure it first! First compilation will take moderate amount of time. + +## Configuration + +By default, the web server starts on `:1323'. Make sure you hide it behind a reverse proxy. + +You will probably need to edit the `reset.gohtml` template to suit your needs. +For now, it contains a reset page in Russian for my hobby mail service. + +The only way to change the configuration is to change the consts in the `main.go` file: + +- `MaddyPath` - path to maddy's database, e.g.: `/var/lib/maddy/credentials.db` +- `HostingURL` - your domain name, for example: `http://localhost:1323/` +- `SMTPMailUsername` - your full email address, for example: `robot@local.host` +- `SMTPMailPassword` - your mailbox password +- `SMTPMailHostname` - your mail hostname, for example: `mx1.local.host` +- `MXServer` - your mail `MX` entry + `PORT`, for example: `mx1.local.host:587` +- `EmailFrom` - the `$FROM` section of an EmailTemplate, for example: `robot@local.host` +- `EmailSubject` - the `$SUBJECT` section of an EmailTemplate +- `EmailMessage` - the `$MESSAGE` section of an EmailTemplate. Remember to provide a password reset link for a user `$RESET_LINK`. For example: `Here's your reset link: $RESET_LINK\r\n` +- `EmailTemplate`- your reset email message +- `HTTPServerPort` - HTTP server port + +`EmailTemplate` example: + +```text +"To: $TO\r\n" + +"From: $FROM\r\n" + +"Content-Type: text/plain; charset=UTF-8\r\n" + +"Subject: $SUBJECT\r\n" + +"\r\n" + +"$MESSAGE\r\n" +``` \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f79e597 --- /dev/null +++ b/go.mod @@ -0,0 +1,36 @@ +module naebet-password-reset + +go 1.20 + +require ( + github.com/akyoto/cache v1.0.6 // indirect + github.com/dustin/go-humanize v1.0.0 // indirect + github.com/golang-jwt/jwt v3.2.2+incompatible // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect + github.com/labstack/echo/v4 v4.10.0 // indirect + github.com/labstack/gommon v0.4.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.16 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect + golang.org/x/crypto v0.2.0 // indirect + golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect + golang.org/x/net v0.4.0 // indirect + golang.org/x/sys v0.3.0 // indirect + golang.org/x/text v0.5.0 // indirect + golang.org/x/time v0.2.0 // indirect + golang.org/x/tools v0.1.12 // indirect + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + lukechampine.com/uint128 v1.2.0 // indirect + modernc.org/cc/v3 v3.40.0 // indirect + modernc.org/ccgo/v3 v3.16.13 // indirect + modernc.org/libc v1.22.2 // indirect + modernc.org/mathutil v1.5.0 // indirect + modernc.org/memory v1.4.0 // indirect + modernc.org/opt v0.1.3 // indirect + modernc.org/sqlite v1.20.4 // indirect + modernc.org/strutil v1.1.3 // indirect + modernc.org/token v1.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..18cf34a --- /dev/null +++ b/go.sum @@ -0,0 +1,96 @@ +github.com/akyoto/cache v1.0.6 h1:5XGVVYoi2i+DZLLPuVIXtsNIJ/qaAM16XT0LaBaXd2k= +github.com/akyoto/cache v1.0.6/go.mod h1:WfxTRqKhfgAG71Xh6E3WLpjhBtZI37O53G4h5s+3iM4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= +github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= +github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= +github.com/labstack/echo/v4 v4.10.0 h1:5CiyngihEO4HXsz3vVsJn7f8xAlWwRr3aY6Ih280ZKA= +github.com/labstack/echo/v4 v4.10.0/go.mod h1:S/T/5fy/GigaXnHTkh0ZGe4LpkkQysvRjFMSUTkDRNQ= +github.com/labstack/gommon v0.4.0 h1:y7cvthEAEbU0yHOf4axH8ZG2NH8knB9iNSoTO8dyIk8= +github.com/labstack/gommon v0.4.0/go.mod h1:uW6kP17uPlLJsD3ijUYn3/M5bAxtlZhMI6m3MFxTMTM= +github.com/mattn/go-colorable v0.1.11/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.2.0 h1:BRXPfhNivWL5Yq0BGQ39a2sW6t44aODpfxkWjYdzewE= +golang.org/x/crypto v0.2.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= +golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU= +golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211103235746-7861aae1554b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab h1:2QkjZIsXupsJbJIdSjjUOgWK3aEtzyuh2mPt3l/CkeU= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/time v0.2.0 h1:52I/1L54xyEQAYdtcSuxtiT84KGYTBGXwayxmIpNJhE= +golang.org/x/time v0.2.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 h1:M8tBwCtWD/cZV9DZpFYRUgaymAYAr+aIUTWzDaM3uPs= +golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +lukechampine.com/uint128 v1.2.0 h1:mBi/5l91vocEN8otkC5bDLhi2KdCticRiwbdB0O+rjI= +lukechampine.com/uint128 v1.2.0/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= +modernc.org/cc/v3 v3.40.0 h1:P3g79IUS/93SYhtoeaHW+kRCIrYaxJ27MFPv+7kaTOw= +modernc.org/cc/v3 v3.40.0/go.mod h1:/bTg4dnWkSXowUO6ssQKnOV0yMVxDYNIsIrzqTFDGH0= +modernc.org/ccgo/v3 v3.16.13 h1:Mkgdzl46i5F/CNR/Kj80Ri59hC8TKAhZrYSaqvkwzUw= +modernc.org/ccgo/v3 v3.16.13/go.mod h1:2Quk+5YgpImhPjv2Qsob1DnZ/4som1lJTodubIcoUkY= +modernc.org/libc v1.22.2 h1:4U7v51GyhlWqQmwCHj28Rdq2Yzwk55ovjFrdPjs8Hb0= +modernc.org/libc v1.22.2/go.mod h1:uvQavJ1pZ0hIoC/jfqNoMLURIMhKzINIWypNM17puug= +modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= +modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/memory v1.4.0 h1:crykUfNSnMAXaOJnnxcSzbUGMqkLWjklJKkBK2nwZwk= +modernc.org/memory v1.4.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sqlite v1.20.4 h1:J8+m2trkN+KKoE7jglyHYYYiaq5xmz2HoHJIiBlRzbE= +modernc.org/sqlite v1.20.4/go.mod h1:zKcGyrICaxNTMEHSr1HQ2GUraP0j+845GYw37+EyT6A= +modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY= +modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw= +modernc.org/token v1.0.1 h1:A3qvTqOwexpfZZeyI0FeGPDlSWX5pjZu9hF4lU+EKWg= +modernc.org/token v1.0.1/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..2af7aba --- /dev/null +++ b/main.go @@ -0,0 +1,230 @@ +package main + +import ( + cryptorand "crypto/rand" + "database/sql" + "github.com/akyoto/cache" + "github.com/labstack/echo/v4" + "github.com/labstack/echo/v4/middleware" + "html/template" + "io" + "log" + "math/big" + _ "modernc.org/sqlite" + "naebet-password-reset/templates" + "net/http" + "net/smtp" + "os/exec" + "strconv" + "strings" + "time" +) + +const ( + // MaddyPath is path to your Maddy credentials database + // + // FYI, Maddy's password database by default is "/var/lib/maddy/credentials.db" + MaddyPath = "" + + // HostingURL is your domain name, + // for example: `http://localhost:1323/` + HostingURL = "" + + // SMTPMailUsername is your full mail address, + // for example: `robot@local.host` + SMTPMailUsername = "" + + // SMTPMailPassword is your mailbox password + SMTPMailPassword = "" + + // SMTPMailHostname is your mail hostname, + // for example: `mx1.local.host` + SMTPMailHostname = "" + + // MXServer is your mail `MX` record + `PORT`, + // for example: `mx1.local.host:587` + MXServer = "" + + // EmailFrom is a EmailTemplate's "$FROM" section + EmailFrom = "" + // EmailSubject is a EmailTemplate's "$SUBJECT" section + EmailSubject = "" + // EmailMessage is a EmailTemplate's "$MESSAGE" section + // + // Remember to provide a password reset link to a user ($RESET_LINK) + EmailMessage = "Here's your reset link: $RESET_LINK\r\n" + // EmailTemplate is your reset mail message + EmailTemplate = "To: $TO\r\n" + + "From: $FROM\r\n" + + "Content-Type: text/plain; charset=UTF-8\r\n" + + "Subject: $SUBJECT\r\n" + + "\r\n" + + "$MESSAGE" + + // CacheTime is the duration that your password reset link will last + CacheTime = 15 * time.Minute + + // HTTPServerPort is an HTTP server port + HTTPServerPort = 1323 +) + +const ( + // TokenAlphabet is created for random string creation, see randomString() function + TokenAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" +) + +func randomString(length int) string { + l := big.NewInt(int64(len(TokenAlphabet))) + res := new(strings.Builder) + for i := 0; i < length; i++ { + n, err := cryptorand.Int(cryptorand.Reader, l) + if err != nil { + panic(err) + } + + res.WriteByte(TokenAlphabet[n.Int64()]) + } + + return res.String() +} + +type Template struct { + templates *template.Template +} + +func (t *Template) Render(w io.Writer, name string, data interface{}, _ echo.Context) error { + return t.templates.ExecuteTemplate(w, name, data) +} + +func main() { + log.Println("[EmailMessage const] Checking your template") + if !strings.Contains(EmailMessage, "$RESET_LINK") { + log.Fatalln("[EmailMessage const] Your message template does not contain $RESET_LINK, so user can't reset his password!") + } + + log.Println("[EmailTemplate const] Checking your template") + if !strings.Contains(EmailTemplate, "$TO") { + log.Fatalln("[EmailTemplate const] Your template does not contain $TO, make sure to add it.") + } + + if !strings.Contains(EmailTemplate, "$FROM") { + log.Fatalln("[EmailTemplate const] Your template does not contain $FROM, make sure to add it.") + } + + if !strings.Contains(EmailTemplate, "$SUBJECT") { + log.Fatalln("[EmailTemplate const] Your template does not contain $SUBJECT, make sure to add it, so user can see a message preview.") + } + + if !strings.Contains(EmailTemplate, "$MESSAGE") { + log.Fatalln("[EmailTemplate const] Your template does not contain $MESSAGE, make sure to add it.") + } + + log.Println("[Sqlite] Loading Maddy's credentials database") + db, err := sql.Open("sqlite", MaddyPath) + if err != nil { + log.Fatalln(err) + } + + // Set up authentication information. + auth := smtp.PlainAuth("", SMTPMailUsername, SMTPMailPassword, SMTPMailHostname) + + log.Println("[Cache] Registering cache for password resets") + passwordResetCache := cache.New(CacheTime) + + log.Println("[Echo] Initializing echo web server") + e := echo.New() + e.HideBanner = true + e.Use(middleware.LoggerWithConfig( + middleware.LoggerConfig{ + Format: `${time_custom} [Echo] ${latency_human} ${method} ${uri} - Error = ${error} - ${remote_ip} "${user_agent}"` + "\n", + CustomTimeFormat: "2006/01/02 15:04:05", + })) + e.Use(middleware.Recover()) + + log.Println("[Echo] Registering Go templates") + t := template.Must(template.ParseFS(templates.Templates, "*.gohtml")) + e.Renderer = &Template{ + t, + } + + e.GET("/reset", func(c echo.Context) error { + return c.Render(http.StatusOK, "reset.gohtml", nil) + }) + + e.POST("/reset", func(c echo.Context) error { + mail := c.FormValue("email") + go func() { + // Check if there is already a password reset + _, exists := passwordResetCache.Get(mail) + if exists { + log.Printf("[Cache] Mail %q already exists in cache, ignoring\n", mail) + return + } + + // Check if it's exists in Maddy db + // It will return an error is there is no user found + var password string + err = db.QueryRow("SELECT value FROM passwords WHERE key = ?", mail).Scan(&password) + if err != nil { + log.Println("[Sqlite] An error occurred while trying to get password from Maddy database:", err) + return + } + + // Generating an unique key + random := randomString(10) + passwordResetCache.Set(random, mail, CacheTime) + + // Connect to the server, authenticate, set the sender and recipient, + // and send the email all in one step. + to := []string{mail} + + msg := strings.ReplaceAll(EmailTemplate, "$TO", mail) + msg = strings.ReplaceAll(msg, "$FROM", EmailFrom) + msg = strings.ReplaceAll(msg, "$SUBJECT", EmailSubject) + msg = strings.ReplaceAll(msg, "$MESSAGE", EmailMessage) + msg = strings.ReplaceAll(msg, "$RESET_LINK", HostingURL+"reset/"+random) + + //msg := []byte(fmt.Sprintf(EmailMessage, mail, SMTPMailUsername, HostingURL+"reset/"+random)) + err := smtp.SendMail(MXServer, auth, SMTPMailUsername, to, []byte(msg)) + if err != nil { + log.Println("[SMTP] Failed to send mail - ", err) + return + } + }() + return c.Render(http.StatusOK, "reset.gohtml", map[string]any{ + "Sent": true, + }) + }) + + e.GET("/reset/:key", func(c echo.Context) error { + key := c.Param("key") + _, exists := passwordResetCache.Get(key) + if !exists { + return c.Redirect(http.StatusTemporaryRedirect, "/reset") + } + return c.Render(http.StatusOK, "reset.gohtml", map[string]any{ + "UniqueLinkTriggered": true, + }) + }) + + e.POST("/reset/:key", func(c echo.Context) error { + key := c.Param("key") + password := c.FormValue("password") + mail, exists := passwordResetCache.Get(key) + if exists { + passwordResetCache.Delete(key) + } + + maddyExecCommand := exec.Command("maddy", "creds", "password", mail.(string), "-p", password) + err = maddyExecCommand.Run() + if err != nil { + log.Println("[maddyExecCommand] Failed to execute Maddy's password reset command - ", err) + return err + } + + return c.String(http.StatusOK, "All good! Your password is now changed.") + }) + + log.Println("[echo] Starting Echo web server") + e.Logger.Fatal(e.Start(":" + strconv.Itoa(HTTPServerPort))) +} diff --git a/templates/embed.go b/templates/embed.go new file mode 100644 index 0000000..8209f5b --- /dev/null +++ b/templates/embed.go @@ -0,0 +1,6 @@ +package templates + +import "embed" + +//go:embed *.gohtml +var Templates embed.FS diff --git a/templates/reset.gohtml b/templates/reset.gohtml new file mode 100644 index 0000000..b905de6 --- /dev/null +++ b/templates/reset.gohtml @@ -0,0 +1,58 @@ + + + + + + + Сброс пароля + + + +

Сброс пароля

+{{ if .UniqueLinkTriggered }} +

Напишите здесь ваш новый пароль

+
+ + +
+{{ else }} + {{ if .Sent }} +

Сообщение о сбросе пароля было отправлено, если такой адрес существует.

+ {{ else }} +
+ + +
+ {{ end }} +{{ end }} + + \ No newline at end of file